如何在css文件中动态添加版本

how to dynamically add the version in the css file?

本文关键字:动态 添加 版本 文件 css      更新时间:2023-09-26

如何使用编译ASP或mb javascript在css文件(例如:main.css?v=1231294012278)中动态添加版本。这解决了缓存的问题

我曾经为此使用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;
    }

试试这个:

<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;
};