How do you cache an image in Javascript

cache images in browser javascript
preload images javascript
preload multiple images javascript
javascript image object
javascript image src
javascript load images in background
javascript function to load image
jquery preload images before page load

My friends and I are working on a website where we would like to cache certain images in order to display them faster in the future. I have two main questions:

  1. How do you cache an image?
  2. How do you use an image once it has been cached? (and just to verify, if an image is cached on page A, it is possible to call it from the cache to use it on page B, right?)

Also, is it possible to set when the cached version of the image will expire?

It would be much appreciated if an example and/or a link to a page which describes this further was included.

We're fine using either raw Javascript or the jQuery version.

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. If you want 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 = [];
    var list = preloadImages.list;
    for (var i = 0; i < array.length; i++) {
        var img = new Image();
        img.onload = function() {
            var index = list.indexOf(this);
            if (index !== -1) {
                // remove image from the array once it's loaded
                // for memory consumption reasons
                list.splice(index, 1);
        img.src = array[i];

preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"]);

This function can be called as many times as you want and each time, it will just add more images to the precache.

Once images have 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.

When precaching as above, the images are loaded asynchronously so they will not block the loading or display of your page. But, if your page has lots of images of its own, these precache images can compete for bandwidth or connections with the images that are displayed in your page. Normally, this isn't a noticeable issue, but on a slow connection, this precaching could slow down the loading of the main page. If it was OK for preload images to be loaded last, then you could use a version of the function that would wait to start the preloading until after all other page resources were already loaded.

function preloadImages(array, waitForOtherResources, timeout) {
    var loaded = false, list = preloadImages.list, imgs = array.slice(0), t = timeout || 15*1000, timer;
    if (!preloadImages.list) {
        preloadImages.list = [];
    if (!waitForOtherResources || document.readyState === 'complete') {
    } else {
        window.addEventListener("load", function() {
        // in case window.addEventListener doesn't get called (sometimes some resource gets stuck)
        // then preload the images anyway after some timeout time
        timer = setTimeout(loadNow, t);

    function loadNow() {
        if (!loaded) {
            loaded = true;
            for (var i = 0; i < imgs.length; i++) {
                var img = new Image();
                img.onload = img.onerror = img.onabort = function() {
                    var index = list.indexOf(this);
                    if (index !== -1) {
                        // remove image from the array once it's loaded
                        // for memory consumption reasons
                        list.splice(index, 1);
                img.src = imgs[i];

preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"], true);
preloadImages(["url99.jpg", "url98.jpg"], true);

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  You have to do three thigs: You need to have a list of image URLs as object or array, for example: var sources = { lion: '/assets/lion.png', monkey: '/assets/monkey.png' }; Define the Function definition, where it receives list of image URLs and a callback function in its arguments list, so when it finishes loading image you can start excution on your web page:

as @Pointy said you don't cache images with javascript, the browser does that. so this may be what you are asking for and may not be... but you can preload images using javascript. By putting all of the images you want to preload into an array and putting all of the images in that array into hidden img elements, you effectively preload (or cache) the images.

var images = [

$(images).each(function() {
var image = $('<img />').attr('src', this);

Preloading Images with JavaScript, Learn how to preload images into the browser's cache using JavaScript. Preloading Images with JavaScript. Step 1: Create a JavaScript Image Object. One of the built-in object types in JavaScript is the Image object. This object can be used to represent Step 2: Load an Image File into the Object. Demonstration of Preloading. Demonstration #2.

There are a few things you can look at:

Pre-loading your images Setting a cache time in an .htaccess file File size of images and base64 encoding them.



There are a couple different thoughts for base64 encoding, some say that the http requests bog down bandwidth, while others say that the "perceived" loading is better. I'll leave this up in the air.

Caching Images With JavaScript and HTML5 progress Bars, Developers have been using the DOM Level 0 Image() object to cache images since almost the beginning of JavaScript's history. Basically it  Finally, you create a for() loop to cycle through the array and assign each one of them to the Image() object, thus preloading it into the cache. The onLoad() event handler

I have a similar answer for asynchronous preloading images via JS. Loading them dynamically is the same as loading them normally. they will cache.

as for caching, you can't control the browser but you can set it via server. if you need to load a really fresh resource on demand, you can use the cache buster technique to force load a fresh resource.

JavaScript Animation: Preloading or Caching Images, For this to happen the image must already be loaded into the computer's memory (also known as cache). If the replacement image isn't already cached it will  une fois qu'une image a été chargée d'une manière ou d'une autre dans le navigateur, elle sera dans la mémoire cache du navigateur et se chargera beaucoup plus rapidement la prochaine fois qu'elle sera utilisée, que cette utilisation soit dans la page courante ou dans toute autre page, à condition que l'image soit utilisée avant qu'elle n'expire dans la mémoire cache du navigateur.

Even though your question says "using javascript", you can use the prefetch attribute of a link tag to preload any asset. As of this writing (Aug 10, 2016) it isn't supported in Safari, but is pretty much everywhere else:

<link rel="prefetch" href="(url)">

More info on support here:

Note that IE 9,10 aren't listed in the caniuse matrix because Microsoft has discontinued support for them.

So if you were really stuck on using javascript, you could use jquery to dynamically add these elements to your page as well ;-)

3+ Ways to Preload Images Using CSS, JavaScript, or Ajax , Three easy ways to preload images using either CSS, JavaScript, the browser will use the preloaded/cached images when rendering the  let myName = localStorage.getItem('name'); myName. Upon typing in the second line, you should see that the myName variable now contains the value of the name data item. The Storage.removeItem () method takes one parameter — the name of a data item you want to remove — and removes that item out of web storage.

A Web Developer's Guide to Browser Caching, The browser will retrieve the HTML page from the web server but consult its cache for the static assets (JavaScript, CSS, images). We can see the  I recommend you apply Cache-Control: no-cache to html files. Applying “no-cache” does not mean that there is no cache at all, it simply tells the browser to validate resources on the server

Precaching images with JavaScript – Crying Glowing Sun, And this technique preload the images into the browser cache when the page initially loads. In order to precache an image we need to construct  Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

Guide for Caching and HTTP Cache Headers for Static Content, It reduces the time it takes for the user to view the images or Javascript or CSS files. This is because the user now accesses the file from his  A catch-block contains statements that specify what to do if an exception is thrown in the try-block. If any statement within the try -block (or in a function called from within the try -block) throws an exception, control is immediately shifted to the catch -block.

  • You don't. The browser does.
  • does the browser cache images automatically?
  • @Logan: Yes, the browser caches images automatically, provided your server sends the necessary headers to tell the browser it's safe to cache it. (These headers may also tell the browser the expiration time, which is part of your question.)
  • how can I verify that my browser is sending the necessary headers?
  • @LoganBesecker You can check Response Headers in the Network section of your browsers dev tools.
  • In this example you are creating a new Image object for each url. If you set the img variable outside of the loop and just update the src, it should have the same effect and cut down on resources
  • @cadlac - But to be certain that the browser would actually dowload and cache each image, you would have to wait until one image finished downloading before setting a new .src property. Otherwise the browser could just stop the prior download and never successfully cache it.
  • It seems to work on newer versions of browsers without waiting, but you make a good point. I'll have to try it out on some older browsers to see it's compatibility :)
  • @cadlac - no need. I updated the code to remove the Image() element from the list when the image finishes loading. It is safer to wait until the image has finished loading.
  • I added another version of the script that waits until other document resources have been loaded so the preloading of images does not compete for bandwidth with the loading of the visible page resources.
  • would it be possible to preload an image on one page(without displaying it), then display it on the next page?
  • to my knowledge if you preload an image on one page it will be entered into the browsers cache and then will display quicker on any other page. if this is wrong, somebody please correct me.
  • Nice nice nice nice!