简体   繁体   中英

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?

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM