I'm looking for a sulotion that check if all images are loaded before they are used in a image slider/rotator. I was thinking of a solution that only show the buttons or thumbnails of the images when the main images are loaded to prevent user from clicking on an image that hasen't been downloaded completey.
Using attributes of <img> to check whether an image is loaded or not. The attributes we will use are: onload: The onload event is triggered when an image is loaded and is executed. onerror: The onerror event is triggered if an error occurs during the execution.
To check if an image is loaded successful or not, you can combine the use of jQuery 'load()' and 'error()' event : $('#image1') . load(function(){ $('#result1'). text('Image is loaded!
The text from the .ready jQuery docs might help make the distinction between load
and ready
more clear:
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.
... and from the .load docs:
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
So .load
is what you're looking for. What's great about this event is that you can attach it to only a subset of the DOM. Let's say you have your slideshow images in a div like this:
<div class="slideshow" style="display:none">
<img src="image1.png"/>
<img src="image2.png"/>
<img src="image3.png"/>
<img src="image4.png"/>
<img src="image5.png"/>
</div>
... then you could use .load
just on the .slideshow
container to trigger once all of the images in the container have been loaded, regardless of other images on the page.
$('.slideshow img').load(function(){
$('.slideshow').show().slideshowPlugin();
});
(I put in a display:none
just as an example. It would hide the images while they load.)
Update (03.04.2013)
This method is deprecated since jQuery Version 1.8
You can trigger off each $('img').load()
event and enable the related link / click event only once your load has triggered. Advantage to doing it image by image is if certain images are taking longer to load you could still allow the quick ones to be 'clickable'.
$('img').load(function() {
// find the related link or click event and enable/add it
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With