Jump to content

can javascript detect when an image has loaded?


DaveNZ

Recommended Posts

Hi, I have been writing a script to reload images without reloading the page.

 

At the moment, while the images are loading the inner HTML of a span tag changes to "Loading" and then setTimeout is used to empty the span again 4 seconds later.

 

However on a slow connection the images can take longer than 4 seconds to load, so the "Loading" phrase disappears before the images have actually loaded.

 

Preferably I would like "Loading" to disappear after all the images have loaded. Is there some way to detect this?

 

 

Link to comment
Share on other sites

There's also the onload property of IMG.  You can set it to do something when the image finishes loading.  If you need to do something once all of the images have loaded, you could use a counter and fire that code once the counter has reached zero.  It is important that you set the onload callback before you set the src property of the image as it may not fire if the image is loaded from cache.

 

function loadMyImages() {
    var counter = 0, image;

    function imgCallback() {
        if (--counter) return;
        // hide the "Loading" SPAN here
    }

    /* show the "Loading" SPAN here */

    for (var i = 0; i < 5; i++) {
        image = document.createElement('IMG');
        image.onload = imgCallback;
        counter++;
        image.src = "image" + i + ".jpg";
    }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.