Home > Blockchain >  How to append a random number (or time in milliseconds) to all links on a page with JavaScript?
How to append a random number (or time in milliseconds) to all links on a page with JavaScript?

Time:11-16

I have a static HTML page at the address https://MyPage/index.html

The page contains several images, which are located at https://MyPage/MyImages

The images are linked in the HTML source code like this:

…<span><img width=x height=y src="MyImages/imageXYZ.png"</span>…

When a button is clicked or, even better, when the page is loaded, all image links should be rewritten by appending a random number or, for example, the current time in milliseconds, so that the links look like this afterwards:

…<span><img width=x height=y src="MyImages/imageXYZ.png?1587624427"</span>…

I believe that possible starting points can be found here:

Changing all links on page

How to Change All Links with javascript

How can I change every link on a page to something new?

Starting from there, how can I add to the examples given such that (instead of a constant redirect) a random number or the time in milliseconds is appended to all image links?

CodePudding user response:

const time_to_img = () => {
  document.querySelectorAll('img').forEach(e => {
    const dateStr = Date.now();
    const date = new Date(dateStr);
    e.src = e.src   '?'   date.getTime();
  })
}
window.addEventListener('load', time_to_img);
<img src="https://picsum.photos/id/1/300/200" alt="">
<img src="https://picsum.photos/id/7/300/200" alt="">
<img src="https://picsum.photos/id/12/300/200" alt="">
<img src="https://picsum.photos/id/22/300/200" alt="">

in the loop you have calculation of time in millisecond which is added to the src of each image after ?

now if you want different number for each image, you'll have to add something (random number?). Here for 4 images everything is done in same millisecond

CodePudding user response:

Thanks! I had done this in the meantime:

<body onl oad="CacheBuster()";>

<script>
function CacheBuster() {
        document.querySelectorAll('img').forEach(e => {
          const dateStr = Date.now();
          const date = new Date(dateStr);
          e.src = e.src   '?'   date.getTime();
        })
    }
</script>

Is that any good? It seems to bl**dy work!

  • Related