首页 > 解决方案 > 如何在 HTML 的 src URL 中添加时间戳

问题描述

我正在尝试在 index.html 中实现缓存破坏。下面是我的代码

<body>
    <app-root></app-root>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="<Value>" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="<Value>" crossorigin="anonymous"></script>
    <script src='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js?v="+ (new Date).getTime()"' integrity="<Value>" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
    <script type="text/javascript" src="https://cdn.rawgit.com/ricmoo/aes-js/e27b99df/index.js"></script>
</body>

我正在尝试在 bootstrap.min.js 路径中添加日期,但是当我在“网络”选项卡中检查链接时,它显示

https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js?v=%22+%20(new%20Date).getTime()%22

我想知道我应该在我的 index.html 文件中放什么,这样我才能得到正确的时间戳值。

标签: htmlcachingbootstrap-4frontend

解决方案


问题是(new Date).getTime()在行

<script src='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js?v="+ (new Date).getTime()"' integrity="<Value>" crossorigin="anonymous"></script>

不是由 Javascript 执行的,因此您只需将其附加为硬编码字符串,这就是您看到该 URL 的原因。

如果您想通过 Javascript 添加时间戳,正确的方法是:

<script>document.write("<script type='text/javascript' src='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js?v=" + Date.now() + "' integrity='<Value>' crossorigin='anonymous'><\/script>");</script>

通过这种方式,您将包含一个脚本,该脚本包含bootstrap.min.js时间戳并将时间戳附加到其 URL。

有关类似问题,请参见此处。

如果您愿意,也可以从服务器端包含时间戳。Java/JSP 示例:

<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js?v=<%= new java.util.Date().getTime() %>" integrity="<Value>" crossorigin="anonymous"></script>

旁注:<Value><script>integrity属性值无效。您应该使用 Bootstrap CDN 提供的值:请参见此处


推荐阅读