日常web开发中,我们修改了js、css等静态资源文件后,如果文件名不变的话,客户端浏览并不会及时获取最新的资源文件,这就很尴尬了
怎么办呢?
1.小白:让客户清除缓存?,No , 不靠谱2.初级:把文件名改了?,可以,但我们产品样式一天更新8百次,怎么办?不方便
...
3.中级:加版本号?,可以,但这个文件,我们有好几个地方用,版本号都加的乱咯? 不方便
4.中高级:自己搞个,一处配置多处更新,.net版 舒服
利用json的键值特性, 此处仅用js,css举例,其他图片等静态资源,都可以使用一、 新建json文件 CssJsVersion.json
{ //请添加需要刷新的js或css文件 //说明:"键值": "指向文件" //"css/common.css": "css/common_20170223.css" "pc/css/common.css": "pc/css/common.css?v=20170829001", "pc/css/active.css": "pc/css/active.css?v=20180620001", "pc/js/GasgooJS.common.base.js": "pc/js/GasgooJS.common.base.js?v=20170816001", "pc/js/event.js": "pc/js/event.js?v=20180508001", "pc/js/events.js": "pc/js/events.js?v=20180111007", "pc/js/masterpage.js": "pc/js/masterpage.js?v=20170918001", "pc/js/home.js": "pc/js/home.js?v=20171013001", "pc/js/af.js": "pc/js/af.js?v=20180810", "wap/css/common.css": "wap/css/common.css?v=20171222001", "wap/css/active.css": "wap/css/active.css?v=20171228001", "wap/css/css.css": "wap/css/css.css?v=20180813001", "wap/js/events.js": "wap/js/events.js?v=20180517002", "wap/js/event.js": "wap/js/event.js?v=20171222005", "wap/js/applyform.js": "wap/js/applyform.js?v=20171228001", "wap/js/masterpage.js": "wap/js/masterpage.js?v=20170918001", "ticket/css/ticket.css": "ticket/css/ticket.css?v=20180608", "pay/css/css.css": "pay/css/css.css?v=20180831"}
二、 新建类ContentConfig.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using Newtonsoft.Json.Linq;using System.IO;using Newtonsoft.Json;////// ContentConfig 的摘要说明/// public class ContentConfig{ private static bool noCache = true; private static JObject BuildItems() { var json = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Content/Json/CssJsVersion.json")); return JObject.Parse(json); } public static JObject Items { get { if (noCache || _Items == null) { _Items = BuildItems(); } return _Items; } } private static JObject _Items; public static T GetValue(string key) { try { return Items[key].Value (); } catch (Exception) { return Items["erro"].Value (); } } public static String[] GetStringList(string key) { return Items[key].Select(x => x.Value ()).ToArray(); } public static String GetString(string key) { return GetValue (key); } public static int GetInt(string key) { return GetValue (key); } public static string GetJsCssVersionUrl(string OldfileName) { string url = Config.RESOURCE_PATH + "/"; try { url += GetString(OldfileName); } catch (Exception)//未找到 OldfileName { url += OldfileName; } return url; } /// /// 把Json文本转为实体 /// ////// /// public static T FromJSON (string input) { try { return JsonConvert.DeserializeObject (input); } catch (Exception ex) { return default(T); } }}
三、调用
js:
css:
" rel="stylesheet" type="text/css" />
5.高级开发:任何打包工具都可以做到,如webpack,grunt,gulp 正在学习...
后语:
1. 第四个方法是笔者实际中使用的,有什么问题,也可以交流交流(* ̄︶ ̄)
2.方法那样使用,但不限于那样使用,随意发挥
3.