js add timestamp to url to solve browser cache

Why is it better to add a timestamp?

During the development process, it is necessary to add a random number to the static resource of html to avoid fetching the local cache file when the version is iterated (if the address is the same, the browser will think that this is the same request), you can give css file, js file Timestamp automatically.

  • html
<fieldset>
    <legend>给url添加时间戳</legend>
    <img id="bgimg" alt="">
 </fieldset>
  • js
<script>
    let cacheImg = document.querySelector('[id="bgimg"]')
    cacheImg.setAttribute('src', timeStamp('bicycle.gif'))

    // 解决项目更换图片浏览器缓存问题
    function timeStamp(url) {
      let currentTime_stamp = new Date().getTime()
      if (url.indexOf('?') > -1) {
        url = url.substr(0, url.indexOf("?")) + "?timestamp=" + currentTime_stamp
      } else {
        url = url + "?timestamp=" + currentTime_stamp
      }
      return url
    }

    var Url = window.location.href;
    //网页URL添加时间戳
    //window.history.pushState 不刷新页面,但是改变页面的url地址
    window.history.pushState({}, 0, timeStamp(Url));
    console.log(window.location.href);
 </script>

insert image description here

Guess you like

Origin blog.csdn.net/qq_43531694/article/details/108842861