Poplava
Poplava

Reputation: 23

Browser image cache and jQuery.load() issue

Code example:

var img = $("img");
var n = img.length;
var i = 0;
function loadImg(i) {
    if( i < n ) {
        $(img[i]).load( function() {
            console.log("img["+i+"] loaded");
            i++;
            loadImg(i);
        });
    } else {
        console.log("img["+i+"] loaded");
        return false;
    }
}
loadImg(0);

This code works, but when image already in a browser cache - jQuery.load is not firing. How can I check to see if the picture is in a browser cache and forcibly fire jQuery.load?

Thanks.

Upvotes: 1

Views: 2904

Answers (2)

Robin van Baalen
Robin van Baalen

Reputation: 3651

Paul Irish has written a neat little plugin for that. It does exactly what you want, including images loaded from cache:

https://github.com/paulirish/jquery.imgloaded

I've updated your fiddle with the above plugin included. This should answer your question:

http://jsbin.com/acuhaf/9/edit

Upvotes: 2

strah
strah

Reputation: 6722

The jQuery documentation says:

Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded.

There are several known caveats with this that should be noted.
These are:
- It doesn't work consistently nor reliably cross-browser
- It doesn't fire correctly in WebKit if the image src is set to the same src as before
- It doesn't correctly bubble up the DOM tree
- Can cease to fire for images that already live in the browser's cache

You may want to use other library to preload images. I would recommend PreloadJS

Upvotes: 1

Related Questions