简体   繁体   中英

Add random variable after image url with javascript

I have a page with an image on it, however this image changes quite frequently, but it has the same URL. To bypass the browser from caching an older version of the image, I want to add a random number variable after the URL. What is the best way to do this with Javascript?

So when the page loads, it does not load:

http://test.com/image.png

instead it loads:

http://test.com/image.png?43673890

So each time the page is reloads, it has a new variable so the latest version of the image is visible.

Give your img tag an id, then you can

document.getElementById("imageid").src=document.getElementById("imageid").src + "?" + Math.random()* 100000000000000000000;

if the initial url has ? then do

document.getElementById("imageid").src=document.getElementById("imageid").src.split('?')[0] + "?" + Math.random()* 100000000000000000000;

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