我能否强制刷新我的样式表文件?

29

我刚刚安静地度过了半天的疯狂。

我正在对Site.css文件中的类进行更改,但我的机器上正在开发的网站没有反映出来。因为我是在学习jQuery,并且正在使用addClass和removeClass玩耍,我正在动态创建这些调用的参数,所以我确定问题出在我的实现上。

结果发现浏览器中缓存了CSS文件,我只需要刷新一下就可以了...

有没有方法可以强制刷新(最好只在调试期间)?

13个回答

0
<link href="~/css/Style.css?t=@DateTime.Now" rel="stylesheet" />

我使用了C#日期时间的简单技巧。

0
你是否在修改 CSS 文件时保持浏览器打开状态?通常,关闭所有浏览器窗口后再进行修改会告诉浏览器下载新的文件副本。

这个方法可以行得通,但是Firefox启动太慢了,不是一个选项。 - GilShalit

0

进一步参考Ian Kemp的答案,该答案利用了所讨论样式表的LastWriteTime,我编写了一个MVC助手来输出带有缓存破坏参数的<link>标签。

代码

public static class CssLinkHelper
{
    public static IHtmlString StyleSheet(this HtmlHelper helper, string stylesheetname)
    {
        // define the virtual path to the css file (see note below)
        var virtualpath = "~/" + stylesheetname;
        // get the real path to the css file
        var realpath = HostingEnvironment.MapPath(virtualpath);
        // get the file info of the css file
        var fileinfo = new FileInfo(realpath);

        // create a full (virtual) path to the css file including a cache busting parameter (e.g. /main.css?12345678)
        var outputpath = VirtualPathUtility.ToAbsolute(virtualpath) + "?" + fileinfo.LastWriteTime.ToFileTime();
        // define the link tag for the style sheet
        var tagdefinition = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" />", outputpath);

        // return html string of the tag
        return new HtmlString(tagdefinition);
    }
}

使用方法

@Html.StyleSheet("main.css")

输出

<link rel="stylesheet" type="text/css" href="/main.css?131393346850223541" />

注意

如果你对 var virtualpath = "/~" + ... 部分感到困惑,并且在想,为什么不直接传递 "~/main.css" 呢?我之所以这样实现这个函数,是因为我所有的 CSS 文件都在一个公共文件夹(/assets)中,而助手将使用公共文件夹名称作为前缀来添加我的输出,即 /assets/main.css?131393346850223541


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接