[removed] url containing random number

前端 未结 4 1475
自闭症患者
自闭症患者 2020-12-19 05:02

A friend is linking my page from his site. As I need users to avoid caching when visiting my page, I want the url to have this form:

http://www.mypage.com/index.php?

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 05:35

    I would add a parameter but you can leave it out if needed:

    var url = "http://www.mypage.com/index.php?rnd="+Math.random()

    or

    var url = "http://www.mypage.com/index.php?rnd="+new Date().getTime()

    Link:

    Mostly random
    

    Note that if you have more than one assignment - for example in a loop, you need to add to the getTime since an iteration of the loop is faster than a millisecond:

    var rnd = new Date().getTime();
    for (var i=0;i

    UPDATE to use the URL constructor with searchParams

    const addRnd = urls => {
      let rnd = new Date().getTime();
      return urls.map((urlStr,i) => {
        let url = new URL(urlStr);
        url.searchParams.set("rnd",rnd+i);  // in case called multiple times
        return url;
      });
    };
    const urls = addRnd( ["http://www.mypage.com/index1.php","http://www.mypage.com/index2.php","http://www.mypage.com/index3.php"])
    console.log(urls)

提交回复
热议问题