How to create a JavaScript callback for knowing when an image is loaded?
.complete
+ callback
This is a standards compliant method without extra dependencies, and waits no longer than necessary:
var img = document.querySelector('img')function loaded() { alert('loaded')}if (img.complete) { loaded()} else { img.addEventListener('load', loaded) img.addEventListener('error', function() { alert('error') })}
Source: http://www.html5rocks.com/en/tutorials/es6/promises/
Image.onload() will often work.
To use it, you'll need to be sure to bind the event handler before you set the src attribute.
Related Links:
Example Usage:
window.onload = function () { var logo = document.getElementById('sologo'); logo.onload = function () { alert ("The image has loaded!"); }; setTimeout(function(){ logo.src = 'https://edmullen.net/test/rc.jpg'; }, 5000); };
<html> <head> <title>Image onload()</title> </head> <body> <img src="#" alt="This image is going to load" id="sologo"/> <script type="text/javascript"> </script> </body> </html>
You can use the .complete property of the Javascript image class.
I have an application where I store a number of Image objects in an array, that will be dynamically added to the screen, and as they're loading I write updates to another div on the page. Here's a code snippet:
var gAllImages = [];function makeThumbDivs(thumbnailsBegin, thumbnailsEnd){ gAllImages = []; for (var i = thumbnailsBegin; i < thumbnailsEnd; i++) { var theImage = new Image(); theImage.src = "thumbs/" + getFilename(globals.gAllPageGUIDs[i]); gAllImages.push(theImage); setTimeout('checkForAllImagesLoaded()', 5); window.status="Creating thumbnail "+(i+1)+" of " + thumbnailsEnd; // make a new div containing that image makeASingleThumbDiv(globals.gAllPageGUIDs[i]); }}function checkForAllImagesLoaded(){ for (var i = 0; i < gAllImages.length; i++) { if (!gAllImages[i].complete) { var percentage = i * 100.0 / (gAllImages.length); percentage = percentage.toFixed(0).toString() + ' %'; userMessagesController.setMessage("loading... " + percentage); setTimeout('checkForAllImagesLoaded()', 20); return; } } userMessagesController.setMessage(globals.defaultTitle);}