I'm adding some <script/>
tags from javascript to load some libraries (e.g., jquery). When all libraries are loaded, I execute main code. To wait until everything's ready, I use solution similar to the one in this answer (found it on the web).
Now, the story: http://jsfiddle.net/EH84z/
function load_javascript(src) {
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = src;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(a, s);
}
load_javascript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js');
function addEvent(elm, evType, fn, useCapture) {
//Credit: Function written by Scott Andrews
//(slightly modified)
var ret = 0;
if (elm.addEventListener) {
ret = elm.addEventListener(evType, fn, useCapture);
} else if (elm.attachEvent) {
ret = elm.attachEvent('on' + evType, fn);
} else {
elm['on' + evType] = fn;
}
return ret;
}
addEvent(window, "load", function() {
console.log(window.jQuery + ' ' + window.$);
$(document);
}, false);
It works fine in Firefox, but quite often fails in Chrome. Every second time I press jsfiddle 'run' button, callback is executed before JQuery is loaded, thus giving error in Chrome console.
Does it mean I misuse addEventListener
horribly? If yes, what's the correct use for it and how do I really wait until all scripts are loaded?
Thanks!
PS Didn't test it in any other browsers yet, so please comment if it's failing somewhere else.
edit
if I wait one second (using setTimout
) before testing, success rate increases to 100%. An example http://jsfiddle.net/EH84z/1/