首页 > 解决方案 > 如何使用 JavaScript 在静态 HTML 网页上为脚本 src 字符串添加 Unix 时间戳?

问题描述

我想出了这个,但它不起作用:

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

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

标签: javascripthtml

解决方案


您不能在 HTML 属性中执行 js。但你可以这样做

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

推荐阅读