vue項目強制清除頁面緩存

異常描述:css

支付寶中內嵌h5項目(vue框架開發),前端從新打包上傳以後訪問頁面會致使頁面空白、頁面tab點擊異常之類異常狀況,須要手動清除支付寶緩存才能夠正常訪問。html

解決方案:前端

在HTTP協議中,只有後端返回 expires 或 Cache-Control:max-age=XXX, 前端才緩存。
但在瀏覽器中,默認會對 html css js 等靜態文件、以及重定向進行緩存,若是在HEAD頭中指定:vue

<HEAD>
<METAHTTP-EQUIV="Pragma"CONTENT="no-cache">
<METAHTTP-EQUIV="Cache-Control"CONTENT="no-cache">
<METAHTTP-EQUIV="Expires"CONTENT="0">
</HEAD>

瀏覽器不會緩存html,可是仍是會對重定向緩存,而且這種方式並不規範,可能有的瀏覽器不支持。
個人最終解決方案是:
1) 對hash過的靜態文件仍是採用默認方式,客戶端會緩存。
2)對html文件,返回時增長頭:Cache-Control,必須每次來服務端校驗,根據etag返回200或者304
對應的nginx配置以下:nginx

 1 upstream example-be {
 2   ip_hash;
 3   server unix:/run/example-be.sock;
 4 }
 5 server{
 6   listen 80; #監聽端口
 7   server_name example.com
 8 
 9   # 後臺api
10   location ~ ^/api {
11     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
12     include uwsgi_params;
13     uwsgi_pass example-be;
14   }
15 
16   # 前端靜態文件
17   location ~* \.(gif|jpg|jpeg|png|css|js|ico|eot|otf|fon|font|ttf|ttc|woff|woff2)$ {
18     root /var/www/example-fe/dist/;
19   }
20 
21   # 前端html文件
22   location / {
23     # disable cache html
24     add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
25 
26     root /var/www/example-fe/dist/;
27     index index.html index.htm;
28     try_files $uri /index.html;
29   }
30 }

因爲瀏覽器緩存靜態文件的時間不可控,咱們能夠在nginx上本身配置expires 1M(1個月)
# 前端靜態文件後端

1 location ~* \.(gif|jpg|jpeg|png|css|js|ico|eot|otf|fon|font|ttf|ttc|woff|woff2)$ {
2   root /var/www/example-fe/dist/;
3   expires 1M;
4   add_header Cache-Control "public";
5 }
相關文章
相關標籤/搜索