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 th
Rather than checking if all images are loaded, why not create the slider/rotator using the $(window).load()
event, rather than the usual $(document).ready()
? $(window).load()
waits for the page to finish loading, including resources such as images, before executing.
See: window.onload vs. body.onload vs. document.onready (also on Stack Overflow).
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
});
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