Javascript - execute after loading all images

After reading other questions, I thought

window.onload=... 

answer my question. I tried this, but it executes the code at the time the page loads (not after loading the images).

If there is any difference, the images come from the CDN and are not relative.

Does anyone know a solution? (I do not use jQuery)

+12
source share
8 answers

Here is a quick hack for modern browsers:

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

Once all the images have been uploaded, your console will display "All images uploaded!".

What this code does:

  • Load all images into a variable from a document
  • Scrolling through these images.
  • Add a listener for the "load" event on each of these images to trigger the incrementCounter function
  • incrementCounter will incrementCounter counter
  • If the counter has reached the length of the images, this means that they are all loaded.

Having this code in a cross browser won't be as complicated, it's just cleaner than that.

+27
source

Promise Pattern solves this problem in the best way, I provided if.js an open source library to solve the problem of loading all images.

 function loadImage (src) { var deferred = when.defer(), img = document.createElement('img'); img.onload = function () { deferred.resolve(img); }; img.onerror = function () { deferred.reject(new Error('Image not found: ' + src)); }; img.src = src; // Return only the promise, so that the caller cannot // resolve, reject, or otherwise muck with the original deferred. return deferred.promise; } function loadImages(srcs) { // srcs = array of image src urls // Array to hold deferred for each image being loaded var deferreds = []; // Call loadImage for each src, and push the returned deferred // onto the deferreds array for(var i = 0, len = srcs.length; i < len; i++) { deferreds.push(loadImage(srcs[i])); // NOTE: We could push only the promise, but since this array never // leaves the loadImages function, it ok to push the whole // deferred. No one can gain access to them. // However, if this array were exposed (eg via return value), // it would be better to push only the promise. } // Return a new promise that will resolve only when all the // promises in deferreds have resolved. // NOTE: when.all returns only a promise, not a deferred, so // this is safe to expose to the caller. return when.all(deferreds); } loadImages(imageSrcArray).then( function gotEm(imageArray) { doFancyStuffWithImages(imageArray); return imageArray.length; }, function doh(err) { handleError(err); } ).then( function shout (count) { // This will happen after gotEm() and count is the value // returned by gotEm() alert('see my new ' + count + ' images?'); } ); 
+12
source

Using window.onload will not work because it fires after the page loads, however, images are not included in this definition of loaded.

A common solution is the ImagesLoaded jQuery plugin.

If you don't like using jQuery at all, you can at least try converting this plugin to pure Javascript. With 93 important lines of code and good commenting, this should not be a difficult task.

+2
source

You might have an onload event on the image that might trigger a function that does the processing ... As for processing, if all the images are loaded, I'm not sure if any of the following mechanisms will work:

has a function that counts the number of images for which onload is called, if this is equal to the total number of images on your page, then perform the necessary processing.

+1
source
  <title>Pre Loading...</title> </head> <style type="text/css" media="screen"> html, body{ margin:0; padding:0; overflow:auto; } #loading{ position:fixed; width:100%; height:100%; position:absolute; z-index:1; ackground:white url(loader.gif) no-repeat center; }** </style> <script> function loaded(){ document.getElementById("loading").style.visibility = "hidden"; } </script> <body onload="loaded();"> <div id="loading"></div> <img id="img" src="avatar8.jpg" title="AVATAR" alt="Picture of Avatar movie" /> </body> 
+1
source

A little late in the game, but I found the following method the simplest:

 function waitForImages () { let isLoading = true while (isLoading) { const loading = [].slice.call(document.images).filter(img => img.complete !== true) if (!loading.length > 0) { isLoading = true return } } } 

Please note that this is blocking code (useful if you are trying to ensure that images are loaded into something like phantomjs)

+1
source

I was about to offer the same thing that Baznya said.

In addition, another possible option, which may not be as reliable, but easy to maintain, is to select the most important / largest image and attach the onload event to only one. The advantage here is that instead of changing the code, if you add more images to your page later.

0
source

This works great:

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

Source: https://habr.com/ru/post/918280/


All Articles