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

前端 未结 9 837
北恋
北恋 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 06:59

    Just take the relevant piece of code from jQuery, John Resig has covered most of the bases on this issue already in jQuery.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-09 07:07

    I found this page, which shows a compact self-contained solution. It seems to work on every browser and has an explanation on how:

    http://www.kryogenix.org/days/2007/09/26/shortloaded

    0 讨论(0)
  • 2020-12-09 07:08

    This works pretty well:

    setTimeout(MyInitFunction, 0);
    
    0 讨论(0)
  • 2020-12-09 07:15

    YUI uses three tests to do this: for Firefox and recent WebKit there's a DOMContentLoaded event that is fired. For older Safari the document.readyState watched until it becomes "loaded" or "complete". For IE an HTML <P> tag is created and the "doScroll()" method called which should error out if the DOM is not ready. The source for YAHOO.util.Event shows YUI-specific code. Search for "doScroll" in the Event.js.

    0 讨论(0)
  • 2020-12-09 07:15

    Why not this:

    <body>  
      <!-- various content -->  
      <script type="text/javascript">  
      <!--  
        myInit();  
      -->
      </script>  
    </body>  
    

    If I understand things correctly, myInit is gonna get executed as soon as browser hit it in the page, which is last thing in a body.

    0 讨论(0)
提交回复
热议问题