Home > database >  can I use JS to add a unix timestamp to <img> end of the src?
can I use JS to add a unix timestamp to <img> end of the src?

Time:03-14

I need add the random int or unix timestamp to all img src="" whit class='avatar'

<img src="a.png" alt="" >
<img src="b.png" alt="" >
<img src="c.png" alt="" >

I know I can use php to set it <img src="a.png?<?php echo time();?>" alt="" >

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.

  1. I prefer use JS don use server side.
  2. the file name is fixed forever, can't change.

any other suggest?

CodePudding user response:

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();
});
  • Related