Question

Is it possible to detect - using jQuery or pure DOM manipulation / events - when an image that was injected into the document has fully loaded? For example, a script needs to replace one image with another. If it just changes the src attribute, the user will see an image disappear briefly (or not so briefly, depending on their connection). So, a better option would be to create a new image element in some hidden place (or, if cross-platformly possible, out of DOM entirely) and switch images only when the new one is ready. Can this be done?

EDIT: It might be a separate question, but still... Is there also a way to detect when an image has failed to load?

Was it helpful?

Solution

You can use image.onload = function(){<...>};

Image is the actual image you want to get the load of.

<img src='...' id='image'>

In order to check if the image finished loading do the following->

document.getElementById('image').onload = function(){<...>} 

or

document.getElementById('image').addEventListener('load',function(){<...>},false);

If you want to check if the image failed to load do this->

document.getElementById('image').onerror = function(){<...>} 

or

document.getElementById('image').addEventListener('error',function(){<...>},false);

Note

.addEventListener method won't work in IE8. If you are planning on supporting it I can edit my answer.

OTHER TIPS

yes you can do that by using the .load() event.

like,

$('#img1').load(function(){  alert('loaded'); });

the alert will be displayed when the resources for that particular selector has loaded fully.

The .load() event does not always work as expected and is prone to fail under different circumstances. For broadest browser support I suggest to use DeSandro's imagesLoaded (which I find to be best practice anyway): https://github.com/desandro/imagesloaded

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top