用户从公众号链接进去h5页面,有时看到的是旧页面,需要手动刷新才能看到最新的页面。手动刷新对用户来说比较繁琐,最好还是在代码里做到自动刷新。
微信内置的浏览器会缓存我们的静态资源,我们可以在打包的时候,给js文件加上时间戳,来解决js文件的缓存问题。
剩下的就是index.html,只要这个文件是最新的,那么引入的js也是最新的。
一种办法是给index.html加上禁用缓存的标签
<!-- 清除缓存标签 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=8">
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Cache" content="no-cache">
这种办法不是总会生效,有时候即便加上了也还是会被缓存。
第二种办法是每次进入index.html页面时自动刷新一下。
<body>
<script>
const refresh_page = localStorage.getItem('refresh_page')
if (refresh_page !== '1') {
localStorage.setItem('refresh_page', '1')
location.reload()
} else {
localStorage.setItem('refresh_page', '0')
}
</script>
<noscript>
<strong>Please enable JavaScript to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
这段代码可以放到body的顶层,通过判断缓存中的一个标识,来决定要不要刷新页面,每当index.html加载到用户的浏览器时,都会先自动刷新一下,确保能否获取到最新的index.html。