views:

122

answers:

2

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/
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/

A: 

Sounds like you are hitting this bug http://dev.jquery.com/ticket/4196

Blair McMillan
+3  A: 

You have to attach the load event to the jQuery script tag, not the window object.

Try this:

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);

    // attach it to the script tag
    addEvent(a, "load", function() {
        console.log(window.jQuery + '  ' + window.$);
        $(document);
    }, false);
}
Luca Matteis
Was just looking up the script load event. You beat me to it. +1
spender
does it differ if you attach the event *first* and then set the src property?
Caspar Kleijne
+1, thanks! I can certainly use one event listener for each script/link tag. But there's another question then: what's the use for window's 'load' event? It's mentioned in lots of places (e.g., the answer I linked). What does it do, then?
Nikita Rybak
@Nikita: The load event on the window object is fired when all resources (the document, objects, images, css, etc) have finished rendering... the one's in the HTML... not the ones you add dynamically. You probably need to call your `load_javascript()` when the window has fired the load event... you can't manipulate the DOM until it is loaded.
Luca Matteis