1. 程式人生 > >thyemleaf:禁用JS緩存

thyemleaf:禁用JS緩存

log time thymeleaf boot work 業務 png RR 獲得

在開發時經常需要調整JS,但是調整後由於頁面緩存的原因,看不到實時效果。

開發環境:springboot+thymeleaf

1.配置文件多模式

技術分享圖片

技術分享圖片

2.獲得當前的激活的模式和隨機數

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component; /** * * 類描述: 項目主配置文件 * */ @Component(value = "app") @ConfigurationProperties(prefix = "app") @PropertySource("classpath:/config/app.properties") public class PropertiesApp { @Autowired private Environment env; private String staticURL; private
String publicURL; private String appURL; public final String getStaticURL() { return staticURL; } public final void setStaticURL(String staticURL) { this.staticURL = staticURL; } public final String getPublicURL() { return publicURL; } public final void setPublicURL(String publicURL) {
this.publicURL = publicURL; } public final String getAppURL() { return appURL; } public final void setAppURL(String appURL) { this.appURL = appURL; } /** * 獲得:隨機數,用作禁用頁面緩存 * * @return the Rint */ public final long getRnd() { return System.currentTimeMillis(); } /** * 獲得激活的配置文件屬性 * * @return */ public String getActive() { return env.getProperty("spring.profiles.active"); } }

3.在頁面中判斷模式和隨機數

<div th:fragment="js-index">
    <th:block th:switch="${@app.getActive()}">
        <script th:case="‘prod‘" type="text/javascript" th:src="(${@app.getAppURL()})+‘js/index.js‘"></script>
        <script th:case="‘dev‘" type="text/javascript" th:src="(${@app.getAppURL()})+‘js/index.js?rnd=‘+(${@app.getRnd()})"></script>
    </th:block>
</div>

${@app.getActive()} 獲得當前的激活模式

${@app.getRnd()} 獲得隨機數

生成的HTML:

技術分享圖片

這樣每次加載的JS都是最新的,記住對業務JS實施,不要對公共的JS去做。

thyemleaf:禁用JS緩存