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.
any other suggest?
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();
});