本文介绍了使用像Stackoverflow这样的查询字符串对CSS文件进行版本控制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你看Stackoverflow.com的源代码,你会看到对他们的css文件的引用是:

If you look at Stackoverflow.com's source you'll see the reference to their css file is:

<link href="/Content/all.min.css?v=2383" rel="stylesheet" type="text/css" />

如何做,这样他们可以通过查询字符串传递一个版本,并提供正确的CSS文件?

How is this done so they can pass a version via query string and have the correct CSS file served up?

推荐答案

文章解释你的想法背后。基本上,你可以发出上次修改文件的时间戳。这样每当你改变你的CSS,查询字符串将改变和强制浏览器下载新版本。这适用于CSS和JS文件。

This (PHP example) article explain you the idea behind it. Basically, you could happend the timestamp of the last time you modified the file. This way everytime you change your CSS, the querystring will change and "forcing" the browser to download the new version. This is valid for both CSS and JS files.

一个ASP.NET示例是:

A ASP.NET sample is this:

public static string GetBreaker(string fileName)
{
    string cacheBreaker = null;
    try
    {
        if (fileName.StartsWith("~"))
        {
            fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName.Remove(0));
        }
        cacheBreaker = File.GetLastWriteTime(fileName).ToFileTime().ToString();
    }
    catch { }

    return string.IsNullOrEmpty(cacheBreaker) ? string.Empty : string.Format("?cachebreaker={0}", cacheBreaker);
}

您可以通过这种方式在MasterPage中调用此方法:

And you call this method in your MasterPage in this way:

<link href="<%= this.ResolveClientUrl("~/CSS/style.css") %><%=CacheBreaker.GetBreaker("~/CSS/style.css") %>"
            rel="stylesheet" type="text/css" />

这篇关于使用像Stackoverflow这样的查询字符串对CSS文件进行版本控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 04:14