Getting notified when the page DOM has loaded (but before [removed])

前端 未结 9 870
北恋
北恋 2020-12-09 06:37

I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the window.onload e

9条回答
  •  無奈伤痛
    2020-12-09 07:06

    Using setTimeout can work quite well, although when it's executed is up to the browser. If you pass zero as the timeout time, the browser will execute when things are "settled".

    The good thing about this is that you can have many of them, and don't have to worry about chaining onLoad events.

    setTimeout(myFunction, 0);
    setTimeout(anotherFunction, 0);
    setTimeout(function(){ doSomething ...}, 0);
    

    etc.

    They will all run when the document has finished loading, or if you set one up after the document is loaded, they will run after your script has finished running.

    The order they run in is not determined, and can change between browsers. So you can't count on myFunction being run before anotherFunction for example.

提交回复
热议问题