How to create a JavaScript callback for knowing when an image is loaded? How to create a JavaScript callback for knowing when an image is loaded? javascript javascript

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>