用ajax清除瀏覽器緩衝的js、css、圖片等

來源:互聯網
上載者:User
用ajax清除瀏覽器緩衝的js、css、圖片等

為了減小瀏覽器與伺服器之間網路傳輸壓力,往往對靜態檔案,如js,css,修飾的圖片做cache,也就是給這些檔案的HTTP回應標頭加入 Expires和Cache-Control參數,並指定緩衝時間,這樣一定時間內瀏覽器就不會給伺服器發出任何的HTTP請求(除了強制重新整理),即使在 這段時間內伺服器的js或css或圖片檔案已經更新多次,但瀏覽器的資料依然是原來最能初cache的舊資料,有沒有辦法讓瀏覽器拿到已經修改後的最新數 據呢?

有,方法是用ajax請求伺服器最新檔案,並加上要求標頭If-Modified-Since和Cache-Control,如下:

$.ajax({
type: "GET",
url: "static/cache.js",
dataType: "text",
beforeSend :function(xmlHttp){
xmlHttp.setRequestHeader("If-Modified-Since","0");
xmlHttp.setRequestHeader("Cache-Control","no-cache");

    }
});

這裡用了jquery.

這樣瀏覽器就會把最新的檔案替換掉本地舊檔案。

當然,這裡還一個問題就是js必須知道伺服器更新了那個js、css、圖片,利用cookie和時間版本應該可以解決.

 

jquery自從1.2開始就有ifModified和cache參數了,不用自己加header

ifModified Boolean Default: false
Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header.

cache Boolean Default: true
Added in jQuery 1.2, if set to false it will force the pages that you request to not be cached by the browser.

$.ajax({
type: "GET",
url: "static/cache.js",
dataType: "text",
cache:false,
ifModified :true
});

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.