Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - execute after all images have loaded

Tags:

javascript

Having read other people's questions I thought

window.onload=... 

would answer my question. I have tried this but it executes the code the instant the page loads (not after the images load).

If it makes any difference the images are coming from a CDN and are not relative.

Anyone know a solution? (I'm not using jQuery)

like image 639
John Wheal Avatar asked Jun 17 '12 12:06

John Wheal


People also ask

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.

Does jQuery wait for images to load?

In jQuery when you do this: $(function() { alert("DOM is loaded, but images not necessarily all loaded"); }); It waits for the DOM to load and executes your code. If all the images are not loaded then it still executes the code.

What is image () in JavaScript?

Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .


1 Answers

Here is a quick hack for modern browsers:

var imgs = document.images,     len = imgs.length,     counter = 0;  [].forEach.call( imgs, function( img ) {     if(img.complete)       incrementCounter();     else       img.addEventListener( 'load', incrementCounter, false ); } );  function incrementCounter() {     counter++;     if ( counter === len ) {         console.log( 'All images loaded!' );     } } 

Once all the images are loaded, your console will show "All images loaded!".

What this code does:

  • Load all the images in a variable from the document
  • Loop through these images
  • Add a listener for the "load" event on each of these images to run the incrementCounter function
  • The incrementCounter will increment the counter
  • If the counter has reached the length of images, that means they're all loaded

Having this code in a cross-browser way wouldn't be so hard, it's just cleaner like this.

like image 70
Florian Margaine Avatar answered Oct 10 '22 14:10

Florian Margaine