Can I force a refresh of my stylesheet file?

I have just spent half a day quietly going mad.

I’m making changes to my classes in the Site.css file and they were not being reflected in the site being developed on my machine. Because I’m learning my way through jQuery and playing with addClass and removeClass and I’m creating the parameters for those calls dynamically, I was sure the problem was in my implementation.

Turns out the CSS file was cached in the browser and all I had to do was refresh it…

Is there a way to force a refresh (preferably only during debug I guess)?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

A popular way of “cache-breaking” is to append a parameter to your css source. Typically a timestamp is used. I prefer the “file last modified” time, ie. filemtime() in PHP. I’m sure there’s an asp.net function that would give you that.

Then your CSS tag becomes:

<link rel="stylesheet" type="text/css" media="screen" href="/main.css?123456789" rel="nofollow noreferrer noopener"/>

with the query parameter changing whenever the CSS file is updated.

Method 2

Press CTRL+F5 to hard-refresh everything on your webpage including scripts and stylesheets.

Additionally, you can incorporate the stylesheets to be served from a dynamic server page [php/asp.net] and the Response.Expires = -1 which will force the client to load the css on every HTTP-GET request explicitly. You can also do this in your webserver settings for CSS mime types.

Method 3

I use this trick:

<link rel="stylesheet" type="text/css" href="cssfile.css?t=<%= DateTime.Now.Ticks %>" rel="nofollow noreferrer noopener" media="screen" />

Method 4

For ASP.NET, the code behind (you can put this in a utility class or master page):

public static string GetTimestampedUrl(string virtualPath)
{
  var realPath = HostingEnvironment.MapPath(virtualPath);
  var file = new FileInfo(realPath);

  return VirtualPathUtility.ToAbsolute(virtualPath) + "?" + file.LastWriteTime.ToFileTime();
}

And then in your page:

<link href="<%= GetTimestampedUrl(" rel="nofollow noreferrer noopener"~/screen.css") %>" rel="stylesheet" type="text/css" media="screen" />

Method 5

One trick is to add a QueryString parameter in the link to your stylesheet

What does ‘?’ do in a Css link?

Method 6

I’m not sure about all browsers, but in IE8 you can use the developer tools…

Go To:

Tools -> Developer Tools (F12)

Then (while on your page) inside the Developer Tools:

Cache -> Always Refresh From Server

Method 7

This is a classic problem. You have a lot of solutions available:

  1. Probably the easiest way is to configure your webserver to server CSS files as never-cache/expire immediately. Obviously you wouldn’t want this on a production environment. With IIS, this is very easy to do.
  2. Add a random value to the name of the file you’re including, e.g. Site.css?v=12. This is what SO does for their includes. I do this in house so that on the development machine, the parameter changes each time (a guid) the file is served, but when deployed it uses the svn version number. A little trickier but more robust.
  3. Many, many more I’m sure

Method 8

For WordPress users, below is the code

<link rel="stylesheet" href="<?php echo get_bloginfo('stylesheet_url')." rel="nofollow noreferrer noopener"?d=".date( 'Ymd', time()); ?>" type="text/css" media="screen" />

Or better one

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); echo '?' . filemtime( get_stylesheet_directory() . '/style.css'); ?>" rel="nofollow noreferrer noopener" type="text/css" media="screen, projection" />

Cheers!

Method 9

My approach is using the “querystring changing” method to bypass caches (even in browser and proxy servers).
Since I’m using Master Pages I maintain the link to CSS as usual like but adding an ID (named here as cssStyleSheet):

<head runat="server">
<link id="cssStyleSheet" href="~/Styles/Default.css" rel="nofollow noreferrer noopener" rel="stylesheet" type="text/css" />

Then at code behind I implemented at Page_Load this line of code, adding a quesrystring like “?t=5343423424234”.

Protected Sub Page_Load(…)

    If IsNothing(Application("CSSTicks")) = True Then
        Application("CSSTicks") = DateTime.Now.Ticks
    End If


    cssStyleSheet.Attributes("href") = cssStyleSheet.Attributes("href") & "?t=" & Application("CSSTicks")

End Sub

Why is that?
At HTML code, some designer could change the CSS file as easy, no interfering at some “difficult” code.
Using an Application variable I avoid spending bandwidth from my servers and also from customer perspective (like using mobiles).

If new application is deployed, the Application variable is reset automatically and a “new” version of CSS if downloaded to browser (even through proxies).

Method 10

The easiest way is to disable caching in your browser. If you can’t or don’t want to do this, you can press ctrl+f5.

Your server or asp application might be caching, too. You can disable this in the web.config or you can restart the development server to make sure the latest version of your file is shown to the user.

Method 11

Are you keeping your browser open between your changes? Often simply closing all browser windows between making changes to your CSS file will tell the browser to download a new copy.

Method 12

To further Ian Kemp’s answer which utilises the LastWriteTime of the style sheet in question, I have written an MVC helper to output the <link> tag with the cache-busting parameter built in.

The Code

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

Usage

@Html.StyleSheet("main.css")

Output

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

Note

In case you’re wondering about the var virtualpath = "/~" + ... part and thinking, why not just pass it in as "~/main.css"? I have implemented this function this way because all my css files are in a common folder (/assets) and the helper will prefix my output with the common folder name i.e. /assets/main.css?131393346850223541

Method 13

<link href="~/css/<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d182a5a8bdb4ffb2a2a2eea5ec9195b0a5b485b8bcb4ff9fbea6">[email protected]</a>" rel="stylesheet" />

I used this simple trick using C# Date Time.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x