0

I am using the following code to dynamically add scripts in JavaScript:

function loadJS(file, c, preventCache)
{
    var jsEl = document.createElement("script");
    if (typeof preventCache === 'undefined' || !preventCache)
        jsEl.src = file;
    else
        jsEl.src = file + "?" + Math.floor((Math.random() * 10000));
    if (c) { jsEl.addEventListener('load', function (e) { c(null, e); }, false); }
    document.getElementsByTagName("head")[0].appendChild(jsEl);
}

Appending "?" + Math.floor((Math.random() * 10000)) disables caching altogether. What I would like to do instead, is append a time stamp of the last modified time of the file. Then the file can be cached but only when it is up to date. How can I efficiently get the last modified time of the file?

Dan Bray
  • 7,242
  • 3
  • 52
  • 70
  • 1
    If you set cache control headers properly, the browser should do this automatically. It can use the `If-Modified-Since` request header to download the file only if it has been changed since the cached version. – Barmar May 23 '17 at 15:26

2 Answers2

0

As far as I know it's not possible: Is it possible with javascript to find file's last modified time?

But there are more efficient ways than a random number. You can use a version number like WordPress does, or use something that changes less regularly (every hour, etc.)

Hooman
  • 1
  • 1
  • 1
0

The file that contains the loadJS, already contains a timestamp generated in PHP. I've decided to include in that file a variable containing the last time any script was modified. I can automate all of that in PHP, considering the JavaScript files are modified from within my website. To do this I will use file_get_contents, modify the line with a timestamp, then file_put_contents. This may seem extremely inefficient but considering, only I will be able to modify JavaScript files and none of my clients will, then I guess it will suffice.

Dan Bray
  • 7,242
  • 3
  • 52
  • 70