JQuery wait for page to finish loading before starting the slideshow?

前端 未结 6 605
囚心锁ツ
囚心锁ツ 2020-12-16 16:31

I have a site with a rotating header image (you\'ve all seen them). I want to do the following:

  1. Load the entire page plus the first header image
  2. Start
6条回答
  •  清歌不尽
    2020-12-16 16:52

    The $(document).ready mechanism is meant to fire after the DOM has been loaded successfully but makes no guarantees as to the state of the images referenced by the page.

    When in doubt, fall back on the good ol' window.onload event:

    window.onload = function()
    {
      //your code here
    };
    

    Now, this is obviously slower than the jQuery approach. However, you can compromise somewhere in between:

    $(document).ready
    (
      function()
      {
        var img = document.getElementById("myImage");
    
        var intervalId = setInterval(
                            function()
                            {
                              if(img.complete)
                              {
                                clearInterval(intervalId);
                                //now we can start rotating the header
                              }
                            },
                            50);
      }
    );
    

    To explain a bit:

    1. we grab the DOM element of the image whose image we want completely loaded

    2. we then set an interval to fire every 50 milliseconds.

    3. if, during one of these intervals, the complete attribute of this image is set to true, the interval is cleared and the rotate operation is safe to start.

提交回复
热议问题