
本文介绍了一个如何通过修改js使html页面更新缓存的示例。与大家分享以供参考。具体的实现方法如下:
许多朋友会遇到这样的情况:如果我们的页面加载了js,则下次打开js缓存文件时就会调用该文件,但是对我们修改后的调试和发布非常不便。本文将讨论如何解决此问题,让我们一起来看看。
一、在后台编写一个UrlCommon js / css url连接操作类



1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Web; 6 using System.Web.Optimization; 7 8 namespace WebApp.Common 9 { 10 public abstract class UrlCommon 11 { 12 public abstract string _defaultTagFormat { get; } 13 public abstract string _verTagFormat { get; } 14 protected internal virtual String ComputeSHA1(String fileName) 15 { 16 String hashSHA1 = String.Empty; 17 if (System.IO.File.Exists(fileName)) 18 { 19 using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)) 20 { 21 System.Security.Cryptography.SHA1 calculator = System.Security.Cryptography.SHA1.Create(); 22 Byte[] buffer = calculator.ComputeHash(fs); 23 calculator.Clear(); 24 StringBuilder stringBuilder = new StringBuilder(); 25 for (int i = 0; i < buffer.Length; i++) 26 { 27 stringBuilder.Append(buffer[i].ToString("x2")); 28 } 29 hashSHA1 = stringBuilder.ToString(); 30 } 31 } 32 return hashSHA1; 33 } 34 public virtual IHtmlString Url(string url, bool ver = true) 35 { 36 string absUrl = System.Web.Optimization.Scripts.Url(url).ToString(); 37 string strUrl = string.Format(this._defaultTagFormat, absUrl); 38 if (ver) 39 { 40 string filePath = System.Web.HttpContext.Current.Server.MapPath(url); 41 string verNum = this.ComputeSHA1(filePath); 42 //if (!string.IsNullOrWhiteSpace(verNum) && verNum.Length > 16) 43 //{ 44 // verNum = verNum.Substring(0, 16); 45 //} 46 strUrl = string.Format(this._verTagFormat, absUrl, verNum); 47 } 48 return new HtmlString(strUrl); 49 } 50 } 51 public class UrlScript : UrlCommon 52 { 53 public static UrlScript Instance = new UrlScript(); 54 public override string _defaultTagFormat 55 { 56 get { return ""; } 57 } 58 public override string _verTagFormat 59 { 60 get { return ""; } 61 } 62 } 63 public class UrlStyle : UrlCommon 64 { 65 public static UrlStyle Instance = new UrlStyle(); 66 public override string _defaultTagFormat 67 { 68 get { return ""; } 69 } 70 public override string _verTagFormat 71 { 72 get { return ""; } 73 } 74 } 75 }

查看代码
二、查看页面添加智能提示


三、使用方法
如何将css / js添加到视图页面
@ UrlStyle.Instance.Url(“〜/ CSS / monther-footer.css”)

@ UrlScript.Instance.Url(“〜/ Scripts / common.js”)
页面加载效果

只要修改了文件,SHA1的值就会更改,并且相应的?v = xxxxxxx也将更改,以便浏览器将自动下载新文件。只要不修改文件,就可以使用本地缓存。犯错的好方法
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/shumachanpin/article-334656-1.html
打