简体   繁体   中英

HTML5 Canvas loading images from browser cache

I've faced this issue everytime I used HTML5 Canvas: I upload an image, drew it into the canvas with this code:

canv = document.getElementById("gc");
canv.width = window.innerWidth;
canv.height = window.innerHeight;
centerX = canv.width / 2;
centerY = canv.height / 2;
ctx = canv.getContext("2d");

image= new Image;
image.src = "images/test.png";
image.onload = function() {
    setInterval(game, 1000 / 500);
};

Everything works fine, the interval call a function that moves the image around the canvas, no errors in console log or anything.

The problem is that when I change (udpate) the file "test.png" on the server, the canvas shows the previous version of the file until I use the clear cache tool for chrome. I thought that the images would load on execution time and everytime would load the image, but it seems it doesn't.

How can I fix it to make it load the actual image file?

A dirty old trick to 'prevent' caching is adding a random number to the request. That way the request - though it is the same picture everytime - is different.

image= new Image();
image.src = "images/test.png?rnd="+Math.random();

You can try adding a nonce like image.src = "test.png?cache=" + Date.now() , though a better approach would be to send a request with the Cache-Control: no-cache header using XMLHttpRequest or fetch .

The reason that "cache-busting" using a pseudo-random querystring is bad, is because it doesn't actually do what the name suggests. Instead it clutters your browser's cache with several redundant resources, each with its own unique querystring. This wastes your disk space ( and lifetime for SSDs ) since you never intend to use the cached resources again.

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