简体   繁体   English

如何为 static HTML 网页上的脚本 src 字符串添加 Unix 时间戳和 Z686155AF75A60ADDF6EZD9?

[英]How do I add a Unix timestamp for a script src string on a static HTML webpage with JavaScript?

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.它必须是src字符串的一部分。 I believe I could do <script> console.log(Date.now()); </script>我相信我可以做到<script> console.log(Date.now()); </script> <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. <script> console.log(Date.now()); </script>如果我只想在浏览器控制台中输入 output Unix 时间戳,但这不是我想要做的。 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.我试图防止浏览器缓存/test.php (处理页面加载日志),并且由于页面本身不是动态提供的,因此我必须在客户端进行。

You can not execute js in HTML attribute.您不能在 HTML 属性中执行 js。 But you could do like this但你可以这样做

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

I suggest you load your script after the page has loaded.我建议您在页面加载后加载脚本。 This way you can dynamically set your script's src attribute:这样您就可以动态设置脚本的src属性:

var script = document.createElement("script");
script.setAttribute("src","/test.php?nocache=" + Date.now());
document.body.appendChild(script);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM