简体   繁体   中英

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:

在此处输入图片说明

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. 在此处输入图片说明 As you can see in the column Size the pictures were already loaded from my cache.

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.

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