Search code examples
javascriptdom-events

I always get the last onload function, but I need both, Is there any other alternate option without removing any of window.onload event?


I always get the last onload function, but I need both, Is there any other alternate option without removing any of window.onload event?

window.onload = function(){
    alert("first");
}

window.onload = function(){
    alert("second");
}

Solution

  • When declaring the second one, you can chain with the first.

    var lastOnLoad = window.onload;
    window.onload = function(){
        lastOnLoad();
        alert("second");
    }
    

    You also can make an utility like this :

    function addOnLoad(f) {
        var lastOnLoad = window.onload;
        window.onload = function() {
            lastOnLoad();
            f();
        }
    }
    

    You'd call it like this :

    addOnLoad(function(){
        alert("first");
    });
    
    addOnLoad(function(){
        alert("second");
    });
    

    EDIT : or you may simply do what ThiefMaster suggests... (I'll upvote him !).