Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript detect if image is in cache

I am currently using jQuery to load an image and fade it in once it is fully loaded. However, I now want to detect if the image I am trying to load is in the browser cache already - and if it is then fade it in after 3 seconds.

Does anyone know how I can do this?

like image 774
user14377 Avatar asked Jul 11 '26 11:07

user14377


2 Answers

There is no browser function to tell you ahead of time if something is in the cache or not.

If you want it cached, you can preload it so that it will most likely be cached when you next want to use it, but there is no way to know if it's already been cached.

You can load an image and then time whether it is loading immediately or not, taking a different course of action if the image loads in less than 1 second (likely coming from the cache) vs. longer (likely coming over the network). This would involve setting an onload handler and a setTimeout() for a short time and acting on whichever happens first.

As always, if you describe for us what problem you're really trying to solve, we can probably give you better advice.

If what you want to do (and this is just a guess from reading your question) is to fadeIn an image in either 3 seconds (if it was cached) or whenever it's loaded (if it was not cached), then you can use code like this to do that:

Working demo: http://jsfiddle.net/jfriend00/XqJpT/

function now() {
    return (new Date()).getTime();
}

function fadeMe(img, always) {
    var self = $(img);
    if (!self.data("faded") && (always || (now() - self.data("baseTime") >= 3000))) {
        self.fadeIn();
        self.data("faded", true);
    }
}

var img = $('<img class="initiallyHidden">')
    .data({
        baseTime: now(),
        faded: false,
        loaded: false
    })
    .appendTo(document.body)
    .load(function() {
        $(this).data("loaded", true);
        fadeMe(this, false);
    })
    .attr("src", "http://photos.smugmug.com/photos/344291068_HdnTo-S.jpg");

setTimeout(function() {
    if (img.data("loaded")) {
        fadeMe(img, true);
    }
}, 3000);

like image 195
jfriend00 Avatar answered Jul 15 '26 19:07

jfriend00


Images have a "complete" property that would presumably be true immediately if the image came out of the cache.

http://www.w3.org/TR/html5/the-img-element.html#dom-img-complete

like image 40
jpsimons Avatar answered Jul 15 '26 19:07

jpsimons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!