Question

I have an image declared in HTML as:

<img src="images/image_01.gif" id="man_img_file" width="400" height="300" alt="image_01" />

I'm changing the image through jQuery:

$('#man_img_file').attr('src', "images/image_02.gif");

Now I want to display a percentage progress bar while the image loads (ie. while the new src image loads through jQuery). How can this be achieved? Can it be done using the jQuery progressbar?

Note: The images are already in the server and I can get the image size through a PHP script prior loading it.

Was it helpful?

Solution 2

Thanks Laurence for sharing.

  1. While changing the 'src' attribute with jQuery, the amount of bytes loaded cannot be checked on the fly (with javascript).
  2. However, while the image is being loaded, a loading message/image can be displayed. (Check the Laurence's answer above for the solution)
  3. As Laurence says, "If you're happy with HTML5 and anything above IE9 you can apparently do this with an XHR: http://blogs.adobe.com/webplatform/2012/01/13/html5-image-progress-events/ (see the sample here: http://blogs.adobe.com/webplatform/files/XHRProgressSample.html?file=XHRProgressSample.html)"

OTHER TIPS

You might not be able to add a progress bar since I don't know a way of determining how much of the image has been loaded just by using Javascript.

However, you could use the Image object and display a rotating "loading" gif while the new image loads:

function LoadNewImage(target, url) {
    var newImage = new Image();

    // some overlay div
    loadingOverlay.show();

    newImage.src = url;

    newImage.onload = function() {
        // image is loaded into browser memory, so will display instantly
        target.attr('src', url);

        // hide the overlay again
        loadingOverlay.hide();
    }
}

Here are some links that might help:

Preload images with javascript

Show a loading overlay

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