2013-11-21 73 views
0

如何使用編譯ASP或mb javascript在css文件中動態添加版本(例如:main.css?v = 123129401278)。這是解決高速緩存的問題如何在css文件中動態添加版本?

+0

你想如何確定文件版本?或者你想只添加隨機參數? – Grundy

回答

0

我以前用ScriptManager來做這個。我檢測ModifiedDateTime並將其添加到該文件,所以它不能被緩存

下面是完整的代碼

<asp:ScriptManager runat="server" EnablePageMethods="true" EnablePartialRendering="true" 
     ID="sm" OnResolveScriptReference="sm_ResolveScriptReference"> 
    <Scripts> 
     <asp:ScriptReference Path="~/scripts/jquery-1.4.2.min.js" /> 
    </Scripts> 
</asp:ScriptManager> 

然後

protected void sm_ResolveScriptReference(object sender, ScriptReferenceEventArgs e) 
     { 
     if (!String.IsNullOrEmpty(e.Script.Path)) 
     { 
      e.AddVersionToScriptPath(Server.MapPath(e.Script.Path)); 
     } 
    } 


public static void AddVersionToScriptPath(this System.Web.UI.ScriptReferenceEventArgs scrArg, string fullpath) 
    { 
     string scriptpath = scrArg.Script.Path; 
     var fn = GetFileWriteTime(fullpath); 
     if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["minifyJS"]) && ConfigurationManager.AppSettings["minifyJS"] == "1") 
      scriptpath = scriptpath.Contains(".min.") ? scriptpath : scriptpath.Replace(".js", ".min.js"); 
     scrArg.Script.Path = String.Format("{0}?{1}", scriptpath, fn); 
    } 

public static string GetFileWriteTime(string fullpath) 
    { 
     string fw = ""; 
     if (File.Exists(fullpath)) 
     { 
      FileInfo fi = new FileInfo(fullpath); 
      fw += fi.LastWriteTime.ToString("yyMMddhhmm"); 
     } 

     return fw; 
    } 
0

試試這個:

<link rel="stylesheet" type="text/css" href="http://mysite/style.css?id="+generateUUID()> 

GenrateUUID

function generateUUID() { 
var d = new Date().getTime(); 
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { 
    var r = (d + Math.random()*16)%16 | 0; 
    d = Math.floor(d/16); 
    return (c=='x' ? r : (r&0x7|0x8)).toString(16); 
}); 
    return uuid; 
};