开发者

How to run a jQuery Code after loading all the images in my page?

开发者 https://www.devze.com 2023-01-15 14:08 出处:网络
How to run a jQuery开发者_开发问答 Code after loading all the images in my page ?$(window).load(function(){})

How to run a jQuery开发者_开发问答 Code after loading all the images in my page ?


$(window).load(function(){})


Checking to see that all images have loaded is slightly involved, so unless you have a pressing need to be so precise, it is much easier to check that all image and everything else has loaded:

$(window).load(function() { ... });

This makes use of the jQuery .load() method.

If you do really need to check for specifically only images, then things get a little trickier. I initially wanted to do this:

$("img").load(function() { ... }); \\ THIS IS INCORRECT!!!!!

However the above creates a jQuery object that contains all images, and then it binds function() { ... } to each of these images. So the above will trigger a function as many times as there are images on the page!

To get around this, we should check how many images there are on the page, and only fire the function once after all those images have been loaded:

$(function() {  

      // To keep track of how many images have loaded
    var loaded = 0;

      // Let's retrieve how many images there are
    var numImages = $("img").length;

      // Let's bind a function to the loading of EACH image
    $("img").load(function() {

          // One more image has loaded
        ++loaded;

          // Only if ALL the images have loaded
        if (loaded === numImages) {

              // This will be executed ONCE after all images are loaded.
            function() { ... }   
        }
    });
});

jsFiddle example


$(function() {
 var length = $('img').length ;
 var counter = 0;
 $('img').each(function() {
     $(this).load(function(){
        counter++;
        if(counter == length) {
           Callback(); //do stuff
        }
     });
   });
});


I did something like this recently, but went about it differently.

$('img').on('load', function(){
    $('img').off('load'); //detaches from load event, so code below only executes once
    // my code to execute
});


Not a direct answer. Still worth referring.

Refer

  1. Run JavaScript Only After Entire Page Has Loaded
  2. jQuery callback on image load (even when the image is cached)

Code

$(window).bind("load", function() {
   // code here
});


@Peter Ajtai answer will work except on IE's cached images. To make it work with IE, here's a solution: https://stackoverflow.com/a/3877079 or by using the imagesLoaded plugin.


For anyone using jquery this little snippet does the trick (it ensures that all images are loaded before any script inside it are run)...

$(window).bind("load", function() {
   // code goes here here
});
0

精彩评论

暂无评论...
验证码 换一张
取 消