I'm using TogetherJS (http://togetherjs.com) and I want to invoke it dynamically once the DOM is ready. When calling it through the script tag in head it works properly. The problem appears when invoking the same script dynamically:
function loadjsfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjsfile("https://togetherjs.com/togetherjs-min.js", "js")
These functions don't work then:
TogetherJS.hub.on('init', function (msg) {
console.log("init");
});
TogetherJS.on("ready", function () {
console.log("ready");
});
I get "TogetherJS is not defined".
What can I do?
Edit: Actually I want to load it after galleria (http://galleria.io) is ready, so I'm calling it like:
Galleria.ready(function(){
loadjsfile("https://togetherjs.com/togetherjs-min.js", "js");
})
Edit2:
Found "Deferring Initialization" section in the docs togetherjs.com/docs/#extending-togetherjs. I just don't know how to replace this line:
MyApp.onload = callback;
I need Galleria's.ready event instead of MyApp.onload .
Adding the script node to the DOM doesn't ensure that the file has finished loading and parsing before subsequent code is executed. Basically, you are trying to execute properties from TogetherJS before they've been created.
Just delay execution until the page has loaded.