Adding multiple onload handlers

前端 未结 4 1609
我在风中等你
我在风中等你 2020-12-03 23:52

I have two js files, each one with its own window.onload handler. Depending on how I attach the two onload handlers to the window object I get a different behaviour on the s

4条回答
  •  旧时难觅i
    2020-12-04 00:48

    Thanks for the answers!

    I rewrote my script2.js using addEventListener and attachEvent like this:

    //addOnloadHandler(initAll1); // it works only when uncommenting this
    addOnloadHandler(initAll2);
    
    function initAll2() {
        alert("initAll2");
        if (linkHasOnclickHandler(document.getElementById("redirect"))) {
            alert("correct!"); 
        }
        else {
            alert("wrong!");
        }
    }
    
    function addOnloadHandler(newFunction) {    
        if (window.addEventListener) { // W3C standard
            window.addEventListener('load', newFunction, false); // NB **not** 'onload'
        }    
        else if (window.attachEvent) { // Microsoft
            window.attachEvent('onload', newFunction);
        }
    }
    
    function linkHasOnclickHandler(element) {
        var oldevent = document.getElementById("redirect").onclick;
        if (typeof oldevent == "function") {
            return true;
        }
        else {
            return false;
        }
    }
    

    As you can see, addOnloadHandler() has been rewritten using the native implementations you guys mentioned. I left script1.js untouched.

    The resulting code still does not work (i.e., the "wrong!" alert message is shown). It only works when I register the onload initAll1() handler twice by uncommenting the first line of code in script2.js.

    Apparently, mixing

    window.onload = handler1;
    

    and

    window.addEventListener('load', handler2, false);
    

    or

    window.attachEvent('onload', handler2);
    

    does not work fine.

    Is there any way to work around this problem that does not imply touching script1.js?

    Just in case you wonder why I don't want to touch script1.js, the reason is that I want my code (script2.js) to be reusable in other projects as well, no matter which other js files each project uses. So, it should work with every possible event-handling registration method used in script1.js.

    thanks once more for your help!

提交回复
热议问题