thyemleaf:禁用JS缓存(原创)

在开发时常常须要调整JS,可是调整后因为页面缓存的缘由,看不到实时效果。javascript

开发环境:springboot+thymeleafjava

1.配置文件多模式spring

image

image

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.在页面中判断模式和随机数 springboot

<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

${@app.getRnd()} 得到随机数 this

生成的HTML:spa

image

这样每次加载的JS都是最新的,记住对业务JS实施,不要对公共的JS去作。code

相关文章
相关标签/搜索