Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 255
faressoft Avatar asked Sep 08 '10 18:09

faressoft


People also ask

How do you check if all images are loaded in jQuery?

To check if an image is loaded successful or not, you can combine the use of jQuery 'load()' and 'error()' event : $('#image1') . load(function(){ $('#result1'). text('Image is loaded!

How do you check if all images are loaded JavaScript?

To determine whether an image has been completely loaded, you can use the HTMLImageElement interface's complete attribute. It returns true if the image has completely loaded and false otherwise. We can use this with naturalWidth or naturalHeight properties, which would return 0 when the image failed to load.

Do things after page load jQuery?

Method 1: Using the on() method with the load event: The on() method in jQuery is used to attach an event handler for any event to the selected elements. The window object is first selected using a selector and the on() method is used on this element.

How do I ensure jQuery is loaded?

In general, you just use the following basic "document loaded" test in jquery. Straight from the beginners jquery tutorial: $(document). ready(function() { // do stuff when DOM is ready });


2 Answers

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

like image 32
Peter Ajtai Avatar answered Sep 27 '22 21:09

Peter Ajtai


$(window).load(function(){})
like image 54
meder omuraliev Avatar answered Sep 27 '22 21:09

meder omuraliev