admin管理员组

文章数量:1323716

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.

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.

Share Improve this question edited Dec 4, 2018 at 14:14 nicholaswmin 23k16 gold badges101 silver badges173 bronze badges asked Dec 4, 2018 at 13:58 ArbreMojoArbreMojo 992 silver badges9 bronze badges 3
  • jsfiddle/7opyw5h4 - it works fine by itself. Possibly something else has overridden the handler. If you're using something like WordPress there might be all kinds of scripts being loaded by the framework. – ADyson Commented Dec 4, 2018 at 14:02
  • One other possibility is that this code is actually inside of another piece of code that runs after the load event fires. (As one example, if this were inside of a click event handler, and you did the click long after the page loaded.) – apsillers Commented Dec 4, 2018 at 14:03
  • Thank you for your answers guys :) I don't think this code is inside of another piece of code, but it's possible that some other scripts of WordPress override the handler, as ADyson said it. I will continue to search :) Thanks a lot again ! – ArbreMojo Commented Dec 4, 2018 at 14:08
Add a ment  | 

1 Answer 1

Reset to default 9

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.

本文标签: javascriptwindowonload function not runningStack Overflow