Search code examples
jqueryimagecachingimage-load

Check if image is already cached with jQuery


I need to add a .load function to an image, however, I do not want this function added if the image is already cached, mainly because in that .load function I fade in the image and hide a loading indicator.

If the image is already cached, I need none of that. Is there a way to check if it's in the cache?

Thanks, Wesley


Solution

  • I appreciate the question was asked a little while ago but I've been looking to solve the same issue, and in case someone else comes across this, here is how I solved it.

    I used a window.setTimeout() with 200ms delay which called my preloader effect, and in the .load() event for the image being loaded, the first thing it does is clear the timeout, so if the load was quick - no effect is shown, but if the image load takes longer than 200ms the preloader is displayed:

    var imgTmr;
    
    imgTmr = window.setTimeout(function() {showLoading('zoomImage');}, 200);
    
    $("#zoomImage").load(function() {
        window.clearTimeout(imgTmr);
        hideLoading();
    }
    
    $("#zoomImage").attr("src", "myLargeImage.jpg");
    
    // The showLoading() and hideLoading() functions just display a wait graphic 
    // the image being loaded in this instance has the id of zoomImage