skip to Main Content

So I have an interesting problem. I have a static site with some HTML files having javascript includes. Is there a way I can add a dynamic timestamp to these JS files in order to override caching and to have the latest version fetched.

Like:

<script async src="://main.lib.js?ts=1606903654"></script>

Earlier I could do this since the HTML was being generated dynamically using PHP. This is no longer the case and I am wondering how I can do this.

Any suggestions would be great!

2

Answers


  1. Create your script element with JS and append it to HEAD.

    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script");
    script.src = "://main.lib.js?ts=" + new Date().getTime();
    script.async = "async";
    head.appendChild(script);
    
    Login or Signup to reply.
  2. Extending @alexP ‘s answer to enable the timestamp to remain constant for at max an hour.

    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script");
    script.src = "://main.lib.js?ts=" + Math.floor((new Date()).setMinutes(0) / 100000);
    script.async = "async";
    head.appendChild(script);
    

    However, I’m not certain if caching will work because it depends on the headers you send with the js file. In simple terms, if the caching works then you don’t need this timestamp

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search