Oto Shavadze
Oto Shavadze

Reputation: 42863

Using window.onload more than 1 times

if i write this

$(document).ready( function () { 
    alert("bla1");
});


$(document).ready( function () { 
    alert("bla2");
});

All good, two alert occurs, but if code is

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


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

second alert not happened, tell someone please, why 2 or more window.onload is wrong?

Upvotes: 2

Views: 3307

Answers (6)

Eyad Bereh
Eyad Bereh

Reputation: 1750

i know my answer is too late,but you can try something like this:

function hello() {
    window.alert("hello");
}

function bye() {
    window.alert("bye");
}

window.addEventListener("load", function() {
    hello();
    bye();
});

Upvotes: 0

TPoschel
TPoschel

Reputation: 3872

Robert Hahn has a good solution on his blog.

function makeDoubleDelegate(function1, function2) {
    return function() {
        if (function1)
            function1();
        if (function2)
            function2();
    }
}

window.onload = makeDoubleDelegate(window.onload, myNewFunction );

The makeDoubleDelegate() function would be put in the first JS file, ready for invokation any time. What it does is accept two functions as arguments, checks to see if they exist, and if so, return an anonymous function containing valid, existing functions.

The first time that window.onload is called, window.onload itself is undefined, so what gets returned is an anonymous function with only myNewFunction() inside. On subsequent window.onload assignments, window.onload does exist, so whatever it holds will be wrapped up with the new function. And so the list grows.

Upvotes: 1

Safari
Safari

Reputation: 3382

you have to use the function addEventListener if you want to achieve the behaviour you want.

window.addEventListener("load",function () {
    alert("bla1");
}, false);

window.addEventListener("load",function () {
    alert("bla2");
}, false);

Upvotes: 3

user1613360
user1613360

Reputation: 1314

Try something like this

function doOnLoad() {
        alert("hi");
        alert("bye");
}
window.onload = doOnLoad;

Upvotes: 1

manish
manish

Reputation: 497

its like

 var test;
 test = 10;
 test = 20 
 alert(test); // 20

Your overwriting it and jQuery handles there on load event differently.

Upvotes: 3

Quentin
Quentin

Reputation: 944474

You assign something to it. You then assign something else to it and overwrite what is there before.

foo = 1;
foo = 2;
// foo is now "2" it is not "1" and "2"

If you want to assign event handlers non-destructively, use addEventListener. You will need to use compatibility methods to support Old-IE. Such methods are built into jQuery via the on method.

Upvotes: 8

Related Questions