Friday, July 06, 2007

Honnan tudjuk, hogy az utolag include-olt javascript mar betoltodott. [2]

Az elozo problemara a codingforums.com-on callback-es megoldast javasolnak a firefoxban az element.addEventListener, IE-ben pedig a onreadystatechange event segitsegevel:


function loadScript(src, callback) {
var node = document.createElement("script");
if (node.addEventListener)
node.addEventListener("load", callback, false);
else
node.onreadystatechange = function() {
if (this.readyState == "complete") callback.call(this);
}
node.src = src;
document.getElementsByTagName("head").item(0).appendChild(node);
node = null;
}


// load 30k script.
// Listener.cleanUp is defined at the bottom of drag.js
callback = function() {
var self = this;
alert("Loaded: " + this.src + "\nListener.cleanUp (nested):" + Listener.cleanUp);
};
loadScript("http://dhtmlkitchen.com/editor/js/drag.js", callback);

[Update]
Ahogy Jan Volter is emliti jobb vigyazni ezzel a readyState propertyvel es onreadystatechange eventtel, mert:
The “this.readyState == ‘complete’” test doesn’t actually entirely work. The readyState theoretically goes through a series of states:

0 uninitialized
1 loading
2 loaded
3 interactive
4 complete

But in fact, states may be skipped. In my experience with IE 7, you get either a loaded event or a completed event, but not both. It may have something to do with whether you are loading from cache or not but there seem to be other factors that influence which events you get. Sometimes I get loading or interactive events too, and sometimes I don’t. It’s possible the test should be “this.readyState == ‘loaded’ || this.readyState == ‘complete’“, but that risks triggering twice.