开发者

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

This question already has answers here: Closed 10 years ago.

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.


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).


If you are asking how the SERVER side can force reloading... One way is to dynamically change the filename of the CSS/JS so that subsequent calls to the page require a different file.

<sarcasm> The other is to simply tell the user to press CTRL-F5 :) </sarcasm>


When finished doing changes to the site change the name of the css manually.


I've not found a way to version App_Themes files (yet), but you can set them to expire in a relatively short period of time (e.g., 10 seconds), which will minimize the cache problem while giving you some performance benefit of caching. Remember, if the file has not changed, the server will respond with 304-Not modified so traffic is reduced even if the browser requests the file.

Add this to the <configuration> section of the Web.Config

<location path="App_Themes">
    <system.webServer>
        <staticContent>
            <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:10" />
        </staticContent>
    </system.webServer>
</location>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜