user1019031
user1019031

Reputation: 751

To be or not to be: window.onload

Silly question but when I write window.onload = alert('hi') I get the alert.

However if I test for its existence: if (window.onload) alert("exists") I get undefined. How come?

Upvotes: 0

Views: 2080

Answers (4)

Christoph
Christoph

Reputation: 51201

Try the following:

if(typeof window.onload !== "undefined") alert("exists!")

This checks explicitly if there is an onload property on the window object.

edit:

The undefined you see is the return value of the alert function.

Upvotes: 0

Quentin
Quentin

Reputation: 943579

You are calling the alert method (which executes immediately) and assigning its return value (undefined) to onload.

If you want to assign a function to onload then you need to assign an actual function, and not the return value of any old function call.

For example:

onload = function () { 
    alert('hi');
};

or

function createHiAlertFunction() {
    return function () {
        alert('hi');
    }
}
onload = createHiAlertFunction();

Generally speaking, however, you should avoid assigning things to the event handler properties and use event binding methods instead. That way you aren't having to juggle things if you want multiple functions to be called.

window.addEventListener('load', function () {
    alert('hi');
});​​​

Note that this isn't supported by old-ish IE, so you probably want to use one of the many libraries (such as YUI or jQuery) that provide an abstraction layer that includes support for the old, proprietary Microsoft way.

Upvotes: 7

Wanderson Silva
Wanderson Silva

Reputation: 1199

window.onload fires an event. By default it has no value, its value is set by the user when something is needed to happen when everything is ready. If you didn't set a value, it will be undefined

Upvotes: 1

Ras
Ras

Reputation: 628

Where do you fire that script? if window.onload returns false it means that the page has not been completly loaded.

Upvotes: -1

Related Questions