PDA

View Full Version : [CLOSED] - Wait for dynamicaly loaded script



hpet
6 Mar 2012, 2:10 AM
Hello!
I use function bellow for dynamicaly loading scripts. Seems to be more or less standard aproach (when reading forums). Never did pay much attention at the callback, till now.
I would like to load "language file", which ofcourse is soon required (login window).
I specified callback function in which I create and show login window. Unfortunately language object is not available yet when callback fires.

What am I missing here?

Thank your for help!



var _loader = new function() {

return {
load: function(url, callback, scope, argList) {

var scriptId = url.replace(/\W/g, "_"); // remove characters that are invalid in an id.

if (Ext.getDom(scriptId)) {
if (typeof callback == "function")
callback.apply(scope || window, argList);
return;
}

var scriptElem = document.createElement('script');
scriptElem.id = scriptId;
scriptElem.src = url + "?" + _app.version;
scriptElem.type = 'text/javascript';

Ext.fly(document.getElementsByTagName('head')[0].appendChild(scriptElem));

if (typeof callback == "function")
Ext.lib.Event.onAvailable(scriptId, callback.createDelegate(scope || window, argList) );
}
}
}

_loader.load("en-EN.js", function() {
var login = new Ext.ForumPanel({....});
});

hpet
6 Mar 2012, 2:18 AM
Ok, I think I understand where my problem is. Callback is actualy fired when "script" object is created (available), which it is... just my object within this script is not yet available.

How would I go and wait for my object? ..some kind of a loop?

hpet
6 Mar 2012, 5:00 AM
I have fixed it.
My loader function was not working properly. I have modifed it and now it fires callback as expected.
This is a new loader function:



var _loader = new function() {

return {
load: function(url, callback, scope, argList) {

var scriptId = url.replace(/\W/g, "_"); // remove characters that are invalid in an id.

if (Ext.getDom(scriptId)) {
if (typeof callback == "function")
callback.apply(scope || window, argList);
return;
}

var scriptElem = document.createElement('script');
scriptElem.id = scriptId;
scriptElem.src = url + "?" + _app.version;
scriptElem.type = 'text/javascript';

if (typeof callback == "function") {
scriptElem.onload = callback; // for cross-browser
scriptElem.onreadystatechange = function() { // for cross-browser
if(this.readyState == 'complete') {
callback();
}
};
}

Ext.fly(document.getElementsByTagName('head')[0].appendChild(scriptElem));
}
}
}