案例:
<!DOCTYPE html>
<html>
<head>
<title>防止浏览器缓存</title>
<script>
function addTimestampToURL() {
var scripts = document.getElementsByTagName('script');
var links = document.getElementsByTagName('link');
// 添加时间戳参数到<script>标签的src属性中
for (var i = 0; i < scripts.length; i++) {
var scriptSrc = scripts[i].getAttribute('src');
if (scriptSrc.indexOf('?') === -1) {
scriptSrc += '?time=' + new Date().getTime();
} else {
scriptSrc += '&time=' + new Date().getTime();
}
scripts[i].setAttribute('src', scriptSrc);
}
// 添加时间戳参数到<link>标签的href属性中
for (var j = 0; j < links.length; j++) {
var linkHref = links[j].getAttribute('href');
if (linkHref.indexOf('?') === -1) {
linkHref += '?time=' + new Date().getTime();
} else {
linkHref += '&time=' + new Date().getTime();
}
links[j].setAttribute('href', linkHref);
}
}
// window.addEventListener 将其绑定到 load 事件上。这样,当页面加载完成后,浏览器会自动调
// 用该函数,从而为 <script> 和 <link> 标签添加时间戳参数。
window.addEventListener('load', function() {
addTimestampToURL();
});
</script>
</head>
<body>
<!-- 页面内容 -->
<script src="min.js"></script>
</body>
</html>
说明:
当浏览器请求一个静态资源时,它会检查该资源是否已经存在于缓存中。如果资源已经被缓存,并且缓存的版本与服务器上的版本相同(通过 URL 判断),浏览器会直接从缓存中获取资源,而不会再次向服务器发送请求。
通过为静态资源的 URL 添加时间戳参数,每次资源内容发生变化时,URL 的参数值也会发生变化,导致浏览器无法命中缓存,因此浏览器会重新发起请求,从服务器获取最新版本的资源。
这种方式确保了浏览器每次都能加载最新的静态资源,而不会使用过期的缓存版本