0

I'm writing a JS 'slideshow' (it's not a normal slideshow: the images change quickly so they have to be preloaded), and I'd like to have a loader on while the images are preloading.
To do this, I suppose I need to detect when each image is loaded (there's 36).
Right now I'm adding the images by appending the tags to the slideshow's main div (and removing the default static image, which users without JS see), but please tell me if you think there's a better way of doing it.
Then they are shown to the user one at the time.
Is there a cross-browser 'native' way of detecting when the images have loaded?
Thank you, StackOverflow!


I think I found an acceptable solution on this site. Still, I'd be happy if you could point out to me any bugs or ways to make the script better!
I did see he leaves out all the ;...

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Sean Bone
  • 3,368
  • 7
  • 31
  • 47
  • possible duplicate of [How can I determine if an image has loaded, using Javascript/jQuery?](http://stackoverflow.com/questions/263359/how-can-i-determine-if-an-image-has-loaded-using-javascript-jquery) – CD.. Jan 29 '12 at 15:31
  • I think I found an acceptable solution (I still haven't tested it though) on this site: http://www.javascriptkit.com/javatutors/preloadimagesplus.shtml. Thanks anyway for answering! – Sean Bone Jan 29 '12 at 17:16

2 Answers2

1

Use the image onload Event:

<img src="..." onload="foo()" />
CD..
  • 72,281
  • 25
  • 154
  • 163
  • Thank you for answering. The problem with this is that I need some way of 'pausing' the loop generating the `` tags until this image has loaded, in order to be sure that _all_ the images have loaded completely before starting the 'slideshow' – Sean Bone Jan 29 '12 at 15:53
1

Try smthing like this

<script type="text/javascript">
    <!--//--><![CDATA[//><!--
        var images = new Array()
        function preload() {
            for (i = 0; i < preload.arguments.length; i++) {
                images[i] = new Image()
                images[i].src = preload.arguments[i]
            }
        }
        preload(
            "http://domain.tld/gallery/image-001.jpg",
            "http://domain.tld/gallery/image-002.jpg",
            "http://domain.tld/gallery/image-003.jpg"
        )
    //--><!]]>
</script>