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
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">
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).
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"/>
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.
I think it's easier, faster and less trouble to handle this issue by disabling caching on the browser than in the server configuration.
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>
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().">";
?>
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
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.
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.
Press F12 on the chrome to open the developer tool
Then right-click on the reload button - Click (Clear Cache and Hard Reload)
Related
I have been looking at a HTML 5 boilerplate template (from http://html5boilerplate.com/) and noticed the use of "?v=1" in URLs when referring to CSS and JavaScript files.
What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?
Not all JavaScript URLs have the "?v=1" (example from the sample below: js/modernizr-1.5.min.js). Is there a reason why this is the case?
Sample from their index.html:
<!-- CSS : implied media="all" -->
<link rel="stylesheet" href="css/style.css?v=1">
<!-- For the less-enabled mobile browsers like Opera Mini -->
<link rel="stylesheet" media="handheld" href="css/handheld.css?v=1">
<!-- All JavaScript at the bottom, except for Modernizr which enables HTML5 elements & feature detects -->
<script src="js/modernizr-1.5.min.js"></script>
<!------ Some lines removed ------>
<script src="js/plugins.js?v=1"></script>
<script src="js/script.js?v=1"></script>
<!--[if lt IE 7 ]>
<script src="js/dd_belatedpng.js?v=1"></script>
<![endif]-->
<!-- yui profiler and profileviewer - remove for production -->
<script src="js/profiling/yahoo-profiling.min.js?v=1"></script>
<script src="js/profiling/config.js?v=1"></script>
<!-- end profiling code -->
These are usually to make sure that the browser gets a new version when the site gets updated with a new version, e.g. as part of our build process we'd have something like this:
/Resources/Combined.css?v=x.x.x.buildnumber
Since this changes with every new code push, the client's forced to grab a new version, just because of the querystring. Look at this page (at the time of this answer) for example:
<link ... href="http://sstatic.net/stackoverflow/all.css?v=c298c7f8233d">
I think instead of a revision number the SO team went with a file hash, which is an even better approach, even with a new release, the browsers only forced to grab a new version when the file actually changes.
Both of these approaches allow you to set the cache header to something ridiculously long, say 20 years...yet when it changes, you don't have to worry about that cache header, the browser sees a different querystring and treats it as a different, new file.
This makes sure you are getting the latest version from of the css or js file from the server.
And later you can append "?v=2" if you have a newer version and "?v=3", "?v=4" and so on.
Note that you can use any querystring, 'v' is not a must for example:
"?blah=1" will work as well.
And
"?xyz=1002" will work.
And this is a common technique because browsers are now caching js and css files better and longer.
The hash solution is nice but not really human readable when you want to know what version of file is sitting in your local web folder. The solution is to date/time stamp your version so you can easily compare it against your server file.
For example, if your .js or .css file is dated 2011-02-08 15:55:30 (last modification) then the version should equal to .js?v=20110208155530
Should be easy to read properties of any file in any language. In ASP.Net it's really easy...
".js?v=" + File.GetLastWriteTime(HttpContext.Current.Request.PhysicalApplicationPath + filename).ToString("yyMMddHHHmmss");
Of coz get it nicely refactored into properties/functions first and off you go. No more excuses.
Good luck, Art.
In order to answer you questions;
"?v=1" this is written only beacuse to download a fresh copy of the css and js files instead of using from the cache of the browser.
If you mention this query string parameter at the end of your stylesheet or the js file then it forces the browser to download a new file, Due to which the recent changes in the .css and .js files are made effetive in your browser.
If you dont use this versioning then you may need to clear the cache of refresh the page in order to view the recent changes in those files.
Here is an article that explains this thing How and Why to make versioning of CSS and JS files
Javascript files are often cached by the browser for a lot longer than you might expect.
This can often result in unexpected behaviour when you release a new version of your JS file.
Therefore, it is common practice to add a QueryString parameter to the URL for the javascript file. That way, the browser caches the Javascript file with v=1. When you release a new version of your javascript file you change the url's to v=2 and the browser will be forced to download a new copy.
During development / testing of new releases, the cache can be a problem because the browser, the server and even sometimes the 3G telco (if you do mobile deployment) will cache the static content (e.g. JS, CSS, HTML, img). You can overcome this by appending version number, random number or timestamp to the URL e.g: JSP: <script src="js/excel.js?time=<%=new java.util.Date()%>"></script>
In case you're running pure HTML (instead of server pages JSP, ASP, PHP) the server won't help you. In browser, links are loaded before the JS runs, therefore you have to remove the links and load them with JS.
// front end cache bust
var cacheBust = ['js/StrUtil.js', 'js/protos.common.js', 'js/conf.js', 'bootstrap_ECP/js/init.js'];
for (i=0; i < cacheBust.length; i++){
var el = document.createElement('script');
el.src = cacheBust[i]+"?v=" + Math.random();
document.getElementsByTagName('head')[0].appendChild(el);
}
As you can read before, the ?v=1 ensures that your browser gets the version 1 of the file. When you have a new version, you just have to append a different version number and the browser will forget about the old version and loads the new one.
There is a gulp plugin which takes care of version your files during the build phase, so you don't have to do it manually. It's handy and you can easily integrate it in you build process. Here's the link: gulp-annotate
As mentioned by others, this is used for front end cache busting. To implement this, I have personally find grunt-cache-bust npm package useful.
I usually after css modification, change the version of css file in master.
then i must upload css file and master file.
is there any solution to change css version without need to upload master.
<link rel="stylesheet" href="<%=ResolveUrl("~/themes/default/style.css?v2") %>" type="text/css"/>
i am using asp.net.
Seeing how you do not want to change anything but the CSS file itself you could write a custom method which wraps ResolveURL and appends the last modified date of the css file in a set format (i.e. MMddyyhhmmss). This would automatically update whenever the file gets changed.
Something along the lines of:
<link href="<%= VersionCssUrl("~/Styles/Site.css") %>" rel="stylesheet" type="text/css" />
C#:
public string VersionCssUrl(string url)
{
// Get physical path.
var path = HttpContext.Current.Server.MapPath(url);
return String.Format("{0}?{1}",
ResolveUrl(url),
File.GetLastWriteTime(path).ToString("MMddyyhhmmss"));
}
Alternatively, it might be worth looking into any of these:
Shinkansen
ClientDependency
Cassette, as mentioned by TJB
.NET built-in bundling
There are lots of automated solutions for this now-a-days
Cassette # http://getcassette.net/ is open source
It will detect changes in the .css files and if you use their markup it will automatically append a hash (so you don't even have to manually update the version!)
They have installation via Nuget which simplifies the configuration / setup.
I'm having a css file and i want to modify it to fit my needs.
The problem is that it seems to be cached somewhere, as i just cannot see the changes, no matter what i do in the css file.
I am sure i am pointing to the right file, as by now i'v modified in it, and it worked.
Is there any setting so that i can turn the cache off?
Thanks!
As pointed out in this article http://www.wkoorts.com/wkblog/2009/07/12/css-auto-reload-with-django-templates/, you could force django reload your css file by using a parameter in your css link :
<link rel="stylesheet" type="text/css" href="/site_media/css/style.css?{% now "U" %}" />
This is a timestamp which takes a different value every second, so you could even reload your css second every second if needed!
Just go into your site, view source, and copy the link to your CSS file. Verify the link, verify it's being modified. Refresh the CSS file manually via your browser to get the latest.
This isn't a Django issue.
Did you try appending a datetime stamp to the end of the request? I know some frameworks do this to .js and .css files automatically to prevent caching.
Instead of using complicated solutions you can add extra parameter to your includes in the templates.
For static includes:
<script src="{% static 'js/polls/polls.js' %}?version=1"></script>
For direct includes:
<link rel="stylesheet" type="text/css" href="/site_media/css/style.css?version=1" />
Note the ?version=1 in the code. Every time you're modifying the file, change this version in the template, so browser will be forced to reload the file.
Of course you can use even now as suggested by #rom, but if your static files are not being changed very often, it's not the smartest idea to don't use cache at all.
I got "dump" isp that always cached internet pages and its css for at least 1 day.
Although the css / js in the server changed, the presented css are not changed (i have been clear my cache everytime)
how to "tell" my isp not to cache some files like css and js ?
thank you !!
at the moment: i'm using proxy to check a under developed web so that it don't get cached ..
The way Stack Overflow itself solves this problem is to add a version parameter to the CSS and JS URLs, which refer to the version of the referenced files:
<link rel="stylesheet" href="http://sstatic.net/so/all.css?v=4542">
Every time the referenced files change, the href attribute of the link tag is updated in the HTML code, thus supporting caching and updated referenced files.
You could try to append some random string to every request of an external file like:
<link href="/css/style.css?cachekiller=1337" media="screen" rel="stylesheet" type="text/css" />
where the 1337 in the above code should be generated randomly for every request e.g.
<?php time() ?>
or something
You can include these documents directly in your HTML files, between <script> or <style> tags. It will obviously make all your HTML files bigger, but that's basically what you're asking.
It's the only way you can be 100% sure that your CSS and JS is not cached at all.
Is there any way of pulling in a CSS stylesheet into FireFox 2 or 3 that is not a static file?
Bellow is the code we are using to pull in a stylesheet dynamically generated by a CGI script.
<link rel="stylesheet" href="/cgi-bin/Xebra?ShowIt&s=LH4X6I2l4fSYwf4pky4k&shw=795430-0&path=customer/DEMO/demo1.css" type="text/css">
/cgi-bin/Xebra?ShowIt&s=LH4X6I2l4fSYwf4pky4k&shw=795430-0&path=customer/DEMO/demo1.css
Note that the URL above that pulls in the CSS does not end with .css rather the parameters do.
Is the Content Type from the server the correct one for the file that is served up?
Content-type: text/css
why isn't this working?
Double check that the response header for the cgi script has
Content-Type: text/css
The extension doesn't matter but you should make sure the content type is "text/css".
I've done the same thing in the past - a former employer's site uses a link tag much like yours, and works fine in FF2 at least (I just checked it, though I tested it in FF when we added that link). If it's not working, I'd suspect it's something about the generated CSS file rather than the importing page. The consensus appears to be the Content-Type from the server may be wrong.
Your server procs (like the CGI) run first, don't they? Seems to me that that link tag will only pull in a file that exists already.
So what I'd do is put a server tag (my lang's ASP/ASP.Net, but you could use PHP or anything, really) in the href.
Like so:
<link rel="stylesheet" type="text/css href="<% =getStylesheetPath() %>" media="all">
Give that a shot.