Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force browsers to reload cached CSS files when using Asp.Net Themes? [duplicate]

Possible Duplicate:
CSS in App_Theme folder gets Cached in Browser

I've seen "What is an elegant way to force browsers to reload cached CSS/JS files?" but the answer there uses PHP and it doesn't address the fact that the CSS is injected dynamically by an ASP.Net Theme.

like image 447
Homer Avatar asked Jan 19 '11 15:01

Homer


People also ask

How do I force the browser to reload cached CSS?

But, if you're not using it, and you just need to reload that one CSS or JS file occasionally in your own browser... just open it in its own tab and hit SHIFT-reload (or CTRL-F5)!

How do I refresh CSS in Chrome?

For Windows in Chrome or Edge, the keyboard shortcut Ctrl + F5 (or Ctrl + Reload) refreshes. For Mac, hold Cmd-Shift-R or Shift-Reload. Most browsers also have a refresh button next to the URL.

How do I force a JavaScript reload?

The easiest solution is the hard reload your browser. Users can hard reload their browser by pressing ctrl + F5 or ctrl + shift + R after opening the application window.

Can we prevent CSS caching?

To disable CSS cache behavior for a given stylesheet means that every user's browser must load that file from scratch, on every page load. This removes the speed benefits of browser caching, but it makes sure that every user is seeing the most updated version of the stylesheet on each and every page load.


1 Answers

I think I have a quick and dirty solution. The trick is to examine the controls within the page header (for example in the PreRender phase), find the links pointing to CSS-files under the App_Themes folder and make them dynamic (by adding some random information to the query-string). This will most likely tell the browser to invalidate the cached version of the file.

The code:

protected void Page_PreRender(object sender, EventArgs e)
{
    HtmlLink link = null;

    foreach (Control c in Header.Controls)
    {
        if (c is HtmlLink)
        {
            link = c as HtmlLink;

            if (link.Href.IndexOf("App_Themes/", StringComparison.InvariantCultureIgnoreCase) >= 0 &&
                link.Href.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase))
            {
                link.Href += string.Format("?t={0}", DateTime.Now.Ticks.ToString());
            }
        }
    }
}

The output:

    <link href="App_Themes/MyTheme/MyTheme.css?t=634310637798128189" 
        type="text/css" rel="stylesheet" />

Note that you need to have a <head runat="server"> declared in your page's markup in order to be able to access the Header property (otherwise it will be null).

like image 89
volpav Avatar answered Sep 23 '22 00:09

volpav