I'm using Less in JS mode (less.js) the following way:
<link rel="stylesheet/less" href="assets/styles/less/bootstrap.less" media="all">
<script src="assets/scripts/libs/less-1.1.5.min.js"></script>
And after some page views, it stops processing the styles and gives a "cached" version. To make it re-parse the styles I have to clear browser cookies. Does anybody knows why is this? Is there any option to make it re-parse on every page view?
Thanks a lot!
UPDATE: Reviewing some of the library code, seems that it uses localStorage to store the stylesheets as a cache. It bases on file's last modified time to update that cache but for some reason it's not working properly because it's not taking my changes...
I just found a issue in GitHub for this. Quoting myself:
This happens to me also in 1.1.5. The script uses localStorage to store the stylesheets. Clearing your browser cache won't work. You must clear it's cookies (logging off all your accounts, %!#^#%) or doing localStorage.clear(). I use this before loading less.js (not using localStorage myself):
<script> /* Provisory for dev environment: */ localStorage.clear(); </script>
When going to production you just compile the stylesheets to .css
Nice find with the localStorage. The quickest solution, then, is to open up your browser's console and run the following command:
localStorage.clear();
Then refresh and you are set.
You can use the following to disable the localStorage cache:
<script>var less=less||{};less.env='development';</script>
<script src="path_to_less.js"></script>
The reason it caches it is because it takes time to generate the css files and that time can add up to a bad user experience if you have a lot of code to compile.
you could put this in your html documents:
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
But that would disable caching of all resources not just your less files.
A better way of doing this would be by passing noCache=1 into the url to clear the browser localStorage when you are developing in less files then it sets a cookie to remember to clear it each time and then you could put noCache=0 to unset the cookie, this way the end user doesn't end up having their localStorage deleted when using your site and you can just leave it in.
$(document).ready(function () {<br>
if(window.location.href.indexOf("noCache=1") > -1) {<br>
$.cookie('noCache', '1', { expires: 1, path: '/' });<br>
localStorage.clear();<br>
}<br>
if(window.location.href.indexOf("noCache=0") > -1) {<br>
$.cookie('noCache', '0', { expires: 1, path: '/' });<br>
}<br>
if ($.cookie('noCache') == '1'){<br>
alert ("disabled Cache");<br>
localStorage.clear();<br>
}<br>
});<br>
<br>
you will need jquery cookie plugin for this to work
you can also add a unique parameter to prevent caching, like this for example if you are using php:
<link rel="stylesheet/less" href="assets/styles/less/bootstrap.less?v=<?= uniqid() ?>" media="all">
Related
New to SASS and have set up a preprocessor through Scout App. When I click save, Scout informs me the updates have been made and changes are shown in the CSS but the changes won't display on my browser.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> The Green Keeper </title>
<link href="https://fonts.googleapis.com/css?family=Raleway|Yesteryear" rel="stylesheet">
<link href= "css/style.css" rel="stylesheet">
</head>
<body>
<header>
<h1> The Green Keeper </h1>
</header>
</body>
</html>
scss
// VARIABLES -------------------------------------->
$color-primary: #E5E5E5;
$font-stack-primary: 'Yesteryear', cursive;
$font-stack-secondary: 'Raleway', sans-serif;
// BASE -------------------------------------->
h1 {
font-family: $font-stack-primary;
color: $color-primary;
}
Old browser caching scenario
Try to add ?v=2 to the href attribute of the css file. Total result:
<link href="css/style.css?v=2" rel="stylesheet">
Sometimes the browser uses the old cached version of the same file, because it tries to optimize time loading of the page, by saving referenced files by their names. With the mentioned trick you can force the browser to reload the new version of the updated file. Some call it version control with cachebusting.
Note: you should always increase the number, in order to see the most updated version immediately. With most module bundlers like webpack or gulp, you can have an automated process that generate this added query string value, computed by hashing the content (better for production, but can be slower for development), or by generating a random number per each compilation (better for development).
However, if you choose to do nothing, the browser will follow the 'cache-control' header of the file, that the server has generated. Some servers have a default value of: max-age=86400, meaning it will stop using the cached version after 24 hours, and will fetch a newer version to be stored again into the cache.
*This wasn't the actual solution in this particular case, but it might be the reason for someone else.
Reference mismatch
The solution for this specific problem was referencing an incorrect path inside the href attribute. We found an error while checking the 'Network' tab inside the browser's devtools: "Failed to load resource: net::ERR_FILE_NOT_FOUND". The solution was to reference the correct path:
<link href= "output/style.css?v=2" rel="stylesheet">
#JC Nolan "You might try it with a random number rather than "2" - or clearing the cache, trying another browser or another computer. If that doesn't work then it's likely something else. Could be internal caching as well on the server side. Adding a "salt" (an internal random element to the CSS could test that as well."
for me, clearing browser cache worked!
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)
EDIT: My sincere apologies! This wasn't an issue with anything but myself - I had a global.css file with correct stuff in it, but below that I included another file with the old CSS in it, in the <head> bit of my HTML. Facepalm.
I have a site I'm developing. I'm using LESS to enhance my CSS to make it easier to write. The problem is, when I change the .less file, the styles rendered in the browser refuse to change. I've looked in the generated .css file, and that updates to reflect the changes made, however the browser doesn't update it's rendered style from the CSS file. I've tried this in Chrome, FF(3 and 4) and Opera, with the same non-updating results.
I've even told the browser to cache nothing, both with PHP and meta tags, to no avail. My Apache config file is almost vanilla, although I am using multiple localhosts (this is a local server). The code used to convert LESS to CSS is given below, and is run every time the page is reloaded:
try
{
lessc::ccompile('global/global.less', 'global/global.css');
}
catch(exception $ex)
{
exit('lessc fatal error:<br />' . $ex->getMessage());
}
There are no exceptions here. the less.php parser checks if the file has been modified, which I removed for a bit, but the CSS file is re-generated on every change, so this must be a caching issue with the browser somewhere... Apache serves up the updated CSS file just fine :-/
Sorry to go on for so long, but I wanted to be clear. If you need anything else, do let me know.
Once I saw in a code the use of timestamp to force the browser to download the css and js files every request, that way:
<link rel="stylesheet" type="text/css" href="http://www.example.com/style.css?ts=<?=time()?>" />
The ?ts=123456789 forces the browser to reload the file whenever the number is different from the previous one.
So I adopted the idea, but instead of timestamp of now, I use timestamp of the modification of file style.css; so it's cached in the browser until be modified on the server:
<link rel="stylesheet" type="text/css" href="http://www.example.com/style.css?ts=<?=filemtime('style.css')?>" />
I'm using LESS and Laravel, and I finally figured out a good solution:
In my <head> tag, I have:
<link rel="stylesheet/less" type="text/css" href="/less/main.less?ts={{FileHelper::getMostRecentModifiedTimeInFolder(realpath(public_path() . '/less'))}}" />
Then I also created a FileHelper class (based on https://stackoverflow.com/a/6767411/470749):
<?php
class FileHelper {
public static function getMostRecentModifiedTimeInFolder($path)
{
//https://stackoverflow.com/a/6767411/470749
$iterator = new DirectoryIterator($path);
$mtime = -1;
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
if ($fileinfo->getMTime() > $mtime) {
$mtime = $fileinfo->getMTime();
}
}
}
return $mtime;
}
}
I might decide to use this approach only on my local development server and use a different approach for production so that it's not always checking file timestamps on every page load.
Since you can't control browser cache, I would suggest you give versions to your css file. Like global.1.11.css.
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.
I’m using a stylesheet as part of a theme and it seems that both IE and Firefox ( or perhaps VS express edition) are caching this stylesheet, since any changes I make to a stylesheet ( such as changing attribute values etc ) aren’t reflected on the displayed page. Any idea how to prevent browser or visual studio from caching this stylesheet?
BTW – only stylesheet is cached, not the entire page
Also, when I've noticed that any changes made to a stylesheet aren’t reflected on a displayed page, I’ve switched from firefox to IE. The first time the page was loaded in IE, page was displayed as it should (reflecting all the changes I’ve made to the stylesheet), but then IE also started caching the stylesheet
thanx
If you have Firefox with the Web Developer toolbar, you can easily disable caching. You can also use Ctrl+F5 to refresh the page. Holding Ctrl tells the browser to perform a forced refresh that ignores the cache.
One option is to link to the stylesheet in a manner that doesn't allow the browser to cache it. I find this is th case when dealing with things like facebook apps and such.
<link type="text/css" rel="stylesheet" href="/styles.css?v=<%= DateTime.Now %>" />
You could try adding version numbers to your css href:
<link rel="stylesheet" type="text/css" href="path/to/stylsheet.css?v1.0.1" />
The query string (v1.0.1) doesn't affect the css as such, but if the number increments the browser reloads the stylesheet (stylesheet.css).
Having the assembly version is also a good idea:
[CB]
protected string GetAssemblyVersion()
{
// get the version object for this assembly
Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
// or do it in pieces
return v.Major + "." + v.Minor + "." + v.Build +"." + v.Revision;
}
[MARKUP]
<link href="/path/to/style.css?v=<%=GetAssemblyVersion() %>" type="text/css" rel="stylesheet" />
This guy has a script you can place in your asp pages, FWIW
You can try hitting the shift button when you click the refresh button -- this always worked for me.
As everyone said, press Ctrl+F5 to refresh the page.
If that isn't working then, is this a page you designed or is it part of a project that is shared in the group? It's possible that who ever coded it might be caching the style sheets or page every so often to reduce bandwidth spent.
You could try using meta tags to indicate that the page is appears to be expired.
For example:
<head id="Head1" runat="server">
<title></title>
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE, must-revalidate, max-age=0" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="Pragma" content="no-cache" />
</head>
I have found that these meta tags aren't always taken into consideration by browsers. IE seems to be the best at detecting that the page shouldn't be cached/the content is expired.
Otherwise, refresh the page to reload the content as has already been suggested.
-Frinny