39

I am learning to develop xhtml, css web pages. Often I am doing changes in CSS but it do not reflect on page because of browser cacheing and if I manually clear cahceing it shows latest code effects. Is there a thing I can put in code to make browker not to cache stuff ? Any advice please

6
  • 2
    This question goes over the many meta tags to prevent caching: stackoverflow.com/questions/1341089/… but your best bet is modifying the headers returned from the server. Commented Oct 20, 2012 at 21:27
  • if you are doing this for development purposes, better turn off cache, what browser are you using ? Commented Oct 20, 2012 at 21:27
  • @Matthew: Good tip, you should add this as an answer. Downside of course - you turn of all caching on the page, not just the CSS. Commented Oct 20, 2012 at 21:31
  • @Matthew: no, I think the best bet for development purposes is to disable caching on the browser instead of messing with server settings. Commented Oct 20, 2012 at 21:31
  • @frenchie: As always, that really depends on your scenario. There are cases where changing the html might be better. If you are testing browser compability for example, you would have to change settings in all browsers then. Or if you are showing the page to different people on different PCs. Commented Oct 20, 2012 at 21:37

11 Answers 11

68

You can append a random query parameter to the stylesheet url (for example via javascript or server side code). It will not change the css file that is being loaded, but it will prevent caching, because the browser detects a different url and will not load the cached stylesheet.

<link rel="stylesheet" type="text/css" href="http://mysite/style.css?id=1234">
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you. Just saved me a lot of time and hassle. +1
function rs( $length = 8 ) { $chars = "abcdefghijklmnopqrstuvwxyz0123456789"; $rs = substr( str_shuffle( $chars ), 0, $length ); return $rs; }
Is this still relative in 2022?
@Abregre I have the feeling it isn't. Conform the comments to this answer: stackoverflow.com/a/1614568/12068558
It is still valid. The important part is that you actually use a random parameter and not just the same every time.
11

You can create class with GetVersion method which will return your application version (or for example build number or build date).

For asp.net application in markup you can then specify something like this:

<script src="Scripts/some.js?version=<%= Common.GetVersion%>" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="~/styles/Style.css?version=<%= Common.GetVersion%>" />

This will force browser to reload files because part of URL to static files will be changed every build (or at least every version).

1 Comment

very nice idea, that way you have caching that gets "reset" when you push a new build
8

With no catching: Put changeable strings at the end of css path, as bellow:

<link rel="stylesheet" type="text/css" href="style.css?2016-12-3:10 13 30"/>

Refresh when version changes:

<link rel="stylesheet" type="text/css" href="style.css?v=1.1.0"/>

Comments

6

If you're using Chrome as your development browser, there are 2 options:

1) When you hold the reload page button down for a second, a menu will appear and offer the possibility to do a hard page reload.

2) In the Inspector settings, you can force the browser to never cache files.

enter image description here

I think it's easier, faster and less trouble to handle this issue by disabling caching on the browser than in the server configuration.

Comments

3

Since the ASP.net tag is also included in the question, I'd like to expand on Maxim Kornilov's answer (https://stackoverflow.com/a/12992813/903783) with how I used his idea of making the URLs webapp-build-specific on ASP.net MVC (his example was in ASP/ASP.net WebForms syntax instead of MVC's and Razor Pages' newer Razor syntax):

1) Added to the webapp's main class (was called MvcApplication) in Global.asax.cs

#region Versioning

public static string Version => typeof(MvcApplication).Assembly.GetName().Version.ToString(); //note: syntax requires C# version >=6

public static DateTime LastUpdated => File.GetLastWriteTime(typeof(MvcApplication).Assembly.Location);

#endregion

the someProperty => someReadOnlyExpression syntax is just shorthand for someProperty { get { return ... ;} } possible since C# 6

2) in its Content/_Layout.cshtml file I used to have the following to show build number and build datetime (based on the webapp's main assembly) on the page footer:

Version @ViewContext.Controller.GetType().Assembly.GetName().Version (@string.Format("{0:yyyy/MM/dd-HH:mm:ss}", @File.GetLastWriteTime(ViewContext.Controller.GetType().Assembly.Location)))

which I changed to the simpler:

Version @somewebappname.MvcApplication.Version (@string.Format("{0:yyyy/MM/dd-HH:mm:ss}", somewebappname.MvcApplication.LastUpdated))

3) it was loading the CSS via hardcoded link in _Layout.cshtml (still refactoring it) which I changed to:

<link href='@Url.Content("~/Content/Site.css?version=" + somewebappname.MvcApplication.Version)' rel="stylesheet" type="text/css" /> 

so if one right-clicks in the webpage and they do view source they see:

<link href='/Content/Site.css?version=2.1.5435.22633' rel="stylesheet" type="text/css" /> 

that is the CSS url is version specific thanks to the dummy parameter version

If a random number was used instead it would fetch the CSS at every page load which is usually undesired, especially if you are already pushing a new webapp build instead of individual page changes to the web server (so that you do have access to a build number that you can inject into URLs).

Note that to achieve auto-incrementing of build number, at Properties/AssemblyInfo.cs I have (see How to have an auto incrementing version number (Visual Studio)?):

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers 
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.*")] //don't use boh AssemblyVersion and AssemblyFileVersion with auto-increment

Comments

1

This can be done through a .htaccess file. Place this code in a file named .htaccess at the root of your website:

<filesMatch "\.(html|htm|js|css)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</filesMatch>

3 Comments

This is if you don't want to manually refresh the cache every time.
This won't work in asp.net; that's not how headers work in the framework.
asp.net has a similar mechanism, but using web.config instead
1

You can use random version id in your link. for example use this:

<link   href=<%="'mystyle.css?version="+ DateTime.Now.ToString("yyyyMMddhhmmss") +"'"%>   rel="stylesheet" type="text/css"/>

where myStyle.css is stylesheet file and DateTime.Now.ToString("yyyyMMddhhmmss") function used for generate random different version id. By using this random version id,browser forced to reload your css.

Comments

1

instead of writing <link> tag using html just use php code. inside <link> tag at the end use php mt_rand() function which will produce a random number and thus your stylesheet will never get cached. <?php echo "<link rel='stylesheet' type='text/css' href='style.css?'".mt_rand().">"; ?>

1 Comment

it should be echo "<link rel='stylesheet' type='text/css' href='style.css?".mt_rand()."'>";
-1

If you are in Google Chrome simply press CTRL + F5 to force said refresh. The CSS will be updated to how it is on your local machine or server. You can also use a .htaccess file, but that is more of a permanent solution to a possibly temporary problem. CSS caching is good for faster page loading, so I do not recommend disabling it entirely.

Comments

-1

I appreciate the user who asked this query. Even today (2025), I faced a similar problem. Here is the solution which I implemented,

<link rel="stylesheet" href="<?= $baseUrl ?>/css/breadcrumb.css?v=<?= time(); ?>">

This fetches the real-time css from the database server rather than retrieving it from cache.

The cause of this issue may be any of the following,

  • Server cache
  • Web browser cache

Comments

-5
  • Press F12 on the chrome to open the developer tool
  • Then right-click on the reload button - Click (Clear Cache and Hard Reload)

7 Comments

Actually ctrl + F5 forces the browser to clear the cache in every browser I know of (mobile excluded obviously).
in common browsers, pressing it once after the page has loaded should be enough to refresh the page's cache
Ankush Jain I am doing same now but I dont want it every time and want some way I may dont have to do this every time and by default browser may not do it.
Pressing just F5, Ctrl+R or GUI Refresh button might won't change anything. Consider pressing(Google Chrome) Shift+F5, Ctrl+Shift+R or Shift+ GUI Refresh button. Also, would you really directly ask the user to force clear the cache? More info: ghacks.net/2018/01/24/… Depends on browser, though.
@AnkushJain You are able to edit your answers. Thus, are you trolling? It's really sad then.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.