Search code examples
javascriptphpbrowserbrowser-cachedom-events

How to force a browser to download and cache an image which is not currently being displayed on the page


I have a web page which displays different images when different links on the same page are clicked. The images are very high quality and they take a lot of time to load, and I want the images to be downloaded and saved in the cache and then loaded on onclick event of the links.


Solution

  • Just load them all as hidden images.

    CSS:

    .hidden {
        display:none;
    }
    

    HTML:

    <img src="/hugeImage.jpg" class="hidden" />
    <img src="/hugeImage2.jpg" class="hidden" />
    <img src="/hugeImage3.jpg" class="hidden" />
    <img src="/hugeImage4.jpg" class="hidden" />
    

    You can easily simulate this with JavaScript, adding each of the images to the DOM after the DOMContentLoaded event - the same logic applies.

    var img = document.createElement('img');
    img.setAttribute('src', '/hugeImage.jpg');
    img.setAttribute('class','hidden');
    document.body.appendChild(img);