'can I use JS to add a unix timestamp to <img> end of the src?
I need add the random int or unix timestamp to all img src="" whit class='avatar'
<img src="a.png" alt="" class="avatar">
<img src="b.png" alt="" class="avatar">
<img src="c.png" alt="" class="avatar">
I know I can use php to set it
<img src="a.png?<?php echo time();?>" alt="" class="avatar">
But I want to try Js to do that.
my code for try, but not work
<script>
var now = Date.now()
var img_src = document.querySelector(".avatar").src;
document.querySelector(".avatar").src = img_src+"?"+now;).
</script>
why add a random int or unix timestamp to the end of img src?
Because I using a CDN
when the user update some photos can't see the new photo on real time.
- I prefer use JS don use server side.
- the file name is fixed forever, can't change.
any other suggest?
Solution 1:[1]
You can get all the images with the querySelectorAll method on the document object.
const images = document.querySelectorAll(".avatar");
After that you can change the src attribute for each of them.
images.forEach((image) => {
image.src = image.src + "?random=" + Date.now();
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Simon Leroux |
