user2303895
user2303895

Reputation: 21

check browser cache before loading external image

I would like to have javascript access the cilent's cache to check if they have an image loaded or not, can I do this or will that give me same origin errors?

Also what happens to websites that do not have

ccess-Control-Allow-Origin set to all?

Upvotes: 2

Views: 3347

Answers (2)

lostsource
lostsource

Reputation: 21830

Not sure what you're trying to do but most browsers take care of that for you.

This means that before requesting the full image it usually sends a 'last modified date' of the cached image to the server, and the server will reply with a 304 unmodified status if the cached resource has not change.

For more information check this link:

http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/

  1. Browser: Hey, give me logo.png, but only if it’s been modified since Mar 16, 2007.
  2. Server: (Checking the modification date)
  3. Server: Hey, you’re in luck! It was not modified since that date. You have the latest version.
  4. Browser: Great! I’ll show the user the cached version.

Upvotes: 1

yzn-pku
yzn-pku

Reputation: 1082

You can use this function (copied from this question) to test whether an image is in cache.

function cached(url) {
    var test = document.createElement("img");
    test.src = url;
    return test.complete || test.width+test.height > 0;
}

The fact is, once the browser has cached the image, there is no additional need for you to load the image from the cache, for the browser will do everything for you.

Thus, just insert a plain . Let the browser do its work.

Upvotes: 2

Related Questions