寫在前面
在app中嵌入h5應用,最頭疼的就是緩存的問題,比如你修改了一個樣式,或者在js中添加了一個方法,發布之后,並沒有更新,加載的仍是緩存里面的內容。這個時候就需要清理緩存才能解決。但又不想讓webview每次都清理緩存,每次都去加載最新的,顯然會影響性能。
解決辦法
解決緩存的方式之一就是在url后面添加一個隨機數可以實現,但我們並不希望每次都是新請求,所以這個時候,我們可以在js或者css的后面添加一個版本號,第一次請求仍是新的請求,之后會將靜態文件進行緩存。一是解決了修改后,無法立即渲染的問題,二是在之后的請求中也會緩存靜態文件。
在asp.net mvc中,我們會把靜態文件放在_Layout.cshtml這個文件中,如下圖
從上面可以看到UrlHelper的類,有了解過HtmlHelper擴展的,很容易想到擴展UrlHelper。
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.Web.Mvc { public static class MyUrlHelper { public static string Scrpit(this UrlHelper helper, string value) { string jsCssVersion = ConfigurationManager.AppSettings["Js_CSS_Version"]; if (string.IsNullOrEmpty(jsCssVersion)) { return helper.Content(value); } else { return helper.Content(string.Format(value + "?_v={0}", jsCssVersion)); } } } }
瀏覽頁面
第一次訪問
刷新頁面
可以看到http狀態碼變為了304 Not Modified狀態。