简体   繁体   中英

How does the JavaScript Image object interact with the browser cache?

I'm using simple objects to wrap Image objects and track when they are loaded, like so:

var preloader = {
    loaded: false,
    image: new Image()
}
preloader.image.onload = function() {
    preloader.loaded = true;
}
preloader.image.src = 'http://www.example.com/image.jpg';

When the image is finished loading, preloader.loaded is set to true. That all works fine.

My question is, what happens when I have so many of these objects and so many images that the browser cache is used up. Eventually once enough images are loaded, the browser will start to dump older ones out of the cache. In that case won't I end up with JavaScript objects where loaded=true, but the image file is not actually cached anymore?

This is hard to test, because I can't tell at any given point which images are still in the cache and which aren't.

Once you've loaded the image from a web page, it's not being used from the cache. It's actually in the browser page memory for the duration of the browser page lifetime or until you get rid of this JS object so it can be garbage collected.

The cache is not used for storage of loaded images on a page. The cache is used so that the next time a load of this image is requested, it can be loaded much faster. If you load so many images that it exceeds the storage of the cache, nothing will happen to the images you have already loaded as they are in browser memory for the duration of the page (independent of the cache). What will happen is that some of the images you loaded will no longer be in the cache so the next time some browser pages wants to load them, they won't be in the cache and will have to be fetched from their original web-site over the internet.

Yesterday I deleted 800MB of internet cache that had built up over the past few months. In short, I don't think it's possible to exhaust the browser cache unless the user has a really old machine, or you're preloading WAY too many images.

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