前言: Springboot推荐使用thymeleaf来进行html开发,而thymeleaf本身提供的方言已经能够带来很便捷的开发体验。在html页面开发时,为了用户体验考虑我们会对js和css进行缓存以减少不必要的服务器请求;另一方面我们也希望当服务器端内容发生变更时用户能及时收到反馈,因此我们需要js/css缓存控制。(当前适用Springboot版本:2.0.3.RELEASE)
1.Springboot配置启用Cache Busting
Springboot官方文档 Static Content Configuration 有提到这点,通过对请求js/css附加md5码方式来保证在js/css内容发生变更时能及时被浏览器加载到:
spring:
thymeleaf:
mode: HTML
cache: false
resources:
chain:
strategy:
content:
enabled: true
paths: /**
2.Thymeleaf模板页面引用
在Server端启用Cache Busting后,页面对于静态资源的引用和普通的html页面稍有不同,如下所示:
<!-- css引用 -->
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<link th:href="@{/css/style.css}" rel="stylesheet">
<!-- js引用 -->
<script th:src="@{/js/plugins/validate/jquery.validate.min.js}"></script>
<script th:src="@{/js/plugins/validate/messages_zh.min.js}"></script>
这样在Thymeleaf模板页面渲染时,实际像服务端请求的静态资源路径如下所示:
css-load.png
js-load.png
由于版本控制时加入的是js/css文件md5码,这样一旦文件发生任何的变更,页面都会重新向服务端请求资源文件。
3.页面缓存的控制
前面提到的是对于js/css缓存的控制,实际上一个页面的缓存分为三块:html内容,js,css。开发过程中经常会遇到的情况是js/css已经变更,但是由于浏览器端的html页面内容一直缓存导致浏览器死活不向服务端重新请求静态资源而直接使用本地缓存。这里还要注意配置禁用浏览器html缓存:
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
后记: 对于使用非Thymeleaf模板引擎的Springboot项目来说,可以用稍微复杂一点的方法达到同样的目的,具体参考链接: SpringBoot Web开发 - 静态资源的缓存