ArbreMojo
ArbreMojo

Reputation: 99

window.onload function not running

I'm facing a weird issue. The console.log() outside the onload function works, but the console.log() inside doesn't work... Would it mean that my page never fully loads ? I had a look at the developer tools of Chrome and it shows me that the page is loaded, so I don't really understand... (here is a screen of the devtool)

Here is my code:

console.log("hello1");

window.onload = function()
{
    console.log("hello2");
};

(I'm using this in a WordPress website, but I don't think it changes anything)

Thanks in advance,

ArbreMojo.

Upvotes: 4

Views: 5319

Answers (1)

nicholaswmin
nicholaswmin

Reputation: 22939

Some other code is probably assigning another function value to the window.onload method, so it basically overrides your assignment.

Instead of window.onload = function you can do:

window.addEventListener('load', function() {
  console.log('loaded')
})

which allows attaching an arbitrary number of handlers for that event. This ensures nothing can override your callback function.

See: EventTarget.addEventListener for more info.

Upvotes: 9

Related Questions