search

Home  >  Q&A  >  body text

JavaScript Tip: Add a random number (or millisecond time) to all links on the page

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

The

page contains several images located at https://MyPage/MyImages

The link to the image in the HTML source code is as follows:

When the button is clicked or better yet the page loads, all image links should be rewritten by adding a random number or e.g. the current time in milliseconds, so that the link looks like this:

I believe a possible starting point can be found here:

Change all links on the page

How to change all links using javascript

How do I change every link on the page to new content?

From there, how do I add (instead of a constant redirect) to the example given so that a random number or millisecond time is appended to all image links?

P粉704196697P粉704196697365 days ago444

reply all(1)I'll reply

  • P粉594941301

    P粉5949413012024-01-17 09:30:49

    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 calculated the time in milliseconds and then added it to the src of each image?

    Now, if you want to use different numbers for each image, you need to add something (random numbers?). Here, for 4 images, all operations are completed within the same millisecond.

    reply
    0
  • Cancelreply