How do you cache an image in Javascript?

Once an image has been loaded in any way into the browser, it will be in the browser cache and will load much faster the next time it is used whether that use is in the current page or in any other page as long as the image is used before it expires from the browser cache.

So, to precache images, all you have to do is load them into the browser. You can generate hidden images, but this method will hold up the page. To precache a bunch of images, it’s probably best to do it with javascript as it generally won’t hold up the page load when done from javascript. You can do that like this:

function preloadImages(array) {
if (!preloadImages.list) {
preloadImages.list = [];
}
for (var i = 0; i < array.length; i++) { var img = new Image(); img.src = array[i]; preloadImages.list.push(img); } } var imageURLs = [ "url1.jpg", "url2.jpg", "url3.jpg" ]; preloadImages(imageURLs); [/php] Then, once they've been preloaded like this via javascript, the browser will have them in its cache and you can just refer to the normal URLs in other places (in your web pages) and the browser will fetch that URL from its cache rather than over the network. Eventually over time, the browser cache may fill up and toss the oldest things that haven't been used in awhile. So eventually, the images will get flushed out of the cache, but they should stay there for awhile (depending upon how large the cache is and how much other browsing is done). Everytime the images are actually preloaded again or used in a web page, it refreshes their position in the browser cache automatically so they are less likely to get flushed out of the cache. The browser cache is cross-page so it works for any page loaded into the browser. So you can precache in one place in your site and the browser cache will then work for all the other pages on your site. Hope this will help for someone 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *