window onload event fails in Chrome

一世执手 提交于 2019-12-11 02:15:12

问题


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/


回答1:


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


来源:https://stackoverflow.com/questions/3889173/window-onload-event-fails-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!