0

I've come up with this, but it doesn't work:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <script src="/test.php?nocache=" + Date.now() + "></script>
    </body>
</html>

It has to be part of the src string. I believe I could do <script> console.log(Date.now()); </script> if all I wanted to do was to output the Unix timestamp in the browser console, but that's not what I'm trying to do. I'm trying to prevent the /test.php (which handles logging of page loads) from being cached by browsers, and since the page itself is not being served dynamically, I have to do it client-side.

  • `` – blex Dec 21 '20 at 17:54
  • 2
    Just send a no-cache header from the php script?! No need to do that by dynamically loading scripts with a cache-busting URI parameter. – Bergi Dec 21 '20 at 17:55
  • Check this post https://stackoverflow.com/questions/7413234/how-to-prevent-caching-of-my-javascript-file – Abrar Hossain Dec 21 '20 at 17:56

2 Answers2

0

You can not execute js in HTML attribute. But you could do like this

<script>
const script=document.createElement('script');
script.src='/test.php?nocache=' + Date.now();
document.head.appendChild(script);
</script>
miniman
  • 61
  • 3
0

I suggest you load your script after the page has loaded. This way you can dynamically set your script's src attribute:

var script = document.createElement("script");
script.setAttribute("src","/test.php?nocache=" + Date.now());
document.body.appendChild(script);
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36