Tim Schmidt
Tim Schmidt

Reputation: 1307

Javascript: How to check if image is already cached

I just started to learn a little bit of JavaScript and i wondered if there is a way to check if an image is already loaded to cache.

In my script im loading some random images from another webpage and display them. When the same image will be displayed the second time, the script won't use the already loaded image, but instead load the same image again, so that there are two of them stored in my cache.

Now I want to check if the image is already stored in cache and if so, use the cached one instead of loading it again.

My code:

<script>
    var img = document.createElement('img');
    var index;

    //On Click create random 3digit number between 1 and 100
    document.getElementById('image').onclick = function(){
        var index = '' + Math.floor(Math.random() * 100 +1);

        while(index.length < 3) {
            index = '0' + index;
        }

        loadImages(index);
    };

    //Load the image with the created number
    function loadImages(id) {
        var src = 'someWebPage/' + id +'.png';            

        img.onload = function () {
            document.getElementById('image').getContext("2d").drawImage(img, 0, 0, 300, 300);
        }

        img.src = src;            
    } 
</script>

Picture of my cache:

enter image description here

As you can see 030.png and 032.png are twice in cache.

Hope you can give me some advice.

EDIT: Just for anyone else that faces this problem, it actually isn´t one at all. Chrome already did everything right, i only did not notice. enter image description here As you can see in the column Size the pictures were already loaded from my cache.

Upvotes: 3

Views: 3789

Answers (1)

vijoc
vijoc

Reputation: 693

The way caching (in this context) is handled is by the browser negotiating with the server using a set of headers to basically tell the server "I already have this version of this resource", to which the server can then respond "OK, that is still valid, no need to download anything new". So you shouldn't be concerned about the caching in the JavaScript side, but instead make sure you are setting the correct Cache-Control headers on the server side. There are likely already questions/answers for your server/framework of choice on how to setup the caching there.

Upvotes: 3

Related Questions