Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Versioning CSS files with a query string like Stackoverflow does? [duplicate]

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" />

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

like image 832
mmcdole Avatar asked Feb 02 '09 08:02

mmcdole


3 Answers

This article (PHP/.htaccess example) explains the idea behind it. Basically, you could append the timestamp of the last time you modified the file to the filename but still serve the original file. This way every time you save a new version of the CSS file, the filename will change which will force the browser to download the new version. This will work for many kinds of files, including both CSS and JS files. (An alternative to using the filename would be using the query string.)

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

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" />
like image 194
Davide Vosti Avatar answered Nov 07 '22 13:11

Davide Vosti


Its so your browser does not cache the css file. And using the version number is handy since the css file could have changed in each version.

It's not a way to call a correct css file. The file is always the same, but the version number makes your browser think otherwise and fetch it again.

like image 30
Ólafur Waage Avatar answered Nov 07 '22 15:11

Ólafur Waage


If you want to know how it is done, they shortly mentioned it in a previous blog entry: it is done automatically by their build process. See this blog post (3rd bullet point).

Unfortunately there are no details, but maybe you can get more information by commenting that blog post or by contacting the stackoverflow team.

like image 2
M4N Avatar answered Nov 07 '22 15:11

M4N