Search code examples
javascripthtmlruby-on-railsopentoktokbox

unable to load javascript in webview until refreshed


i have an html file called room.html.erb which has some js code.when i click on a link it has to load the above page.but the page is loading correctly except js code.when i refresh it working fine.

code in room.html.erb

<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>

<script>
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=@group.sessionId%>" ;
var token = "<%=@opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);

session = OT.initSession(apiKey,sessionId);

session.on
({
    streamCreated: function(event)
    {
        session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
    }
});

session.connect(token,function(error){
    if(error)
    {
        console.log(error.message);
    }
    else{
        session.publish('myPublisherDiv',{width: 320,height: 240});
    }
}); 

</script>

i couldn't able to figure it out why it is happening.


Solution

  • Wait until the DOM is loaded?

    <script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function(event) { 
        var apiKey = xxxxxx;//my apikey
        var sessionId ="<%=@group.sessionId%>" ;
        var token = "<%=@opentok_token%>";
        var session;
        OT.setLogLevel(OT.DEBUG);
    
        session = OT.initSession(apiKey,sessionId);
    
        session.on
        ({
            streamCreated: function(event)
            {
                session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
            }
        });
    
        session.connect(token,function(error){
            if(error)
            {
                console.log(error.message);
            }
            else{
                session.publish('myPublisherDiv',{width: 320,height: 240});
            }
        }); 
    });
    </script>
    

    another method

    add

    <div id="myPublisherDiv"></div>
    <div id="subscribersDiv"></div>