HTML5 offline appcache: Force refresh of all content? - html

My small HTML5 app needs to be re-deployed on a server. I understood I only had to touch the .appcache file to have every browser update to the last version of the files upon next visit.
The manifest looks like this:
CACHE MANIFEST
#Version: 201209251353
index.html
apple-touch-icon.png
css/styles.css
data/dump.bin
img/background.png
img/sprites.png
js/core.js
js/jquery-1.8.1.min.js
vid/walkthrough.mov
To "touch", I added a comment (#Version:) which I mean to be updated any time the content changes.
Strangely, some files are updated. Not all, for isntance, a colleague gets the latest core.js, but still displays an old walkthrough.mov.
Is there a simple mechanism to force update all files from the cache?
I found the following code on SO and included it in the scripts, expecting it to help. Not sure how needful it is :(
// Application cache refresh
window.addEventListener('load', function(e) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new hotness.
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {
// Manifest didn't changed. Nothing new to server.
}
}, false);
}, false);

What expiry headers are you setting on your manifest and content?
If you've set (for example) the expiry on vid/walkthrough.mov to be one month in the future and that file is small enough to go in the browser cache (note: not the application cache) then the browser will refresh the application cache from the version in the browser cache rather than requesting it across the network again (if it's less than a month since it fetched the file).
If you've set a future expiry date on the manifest file then in some versions of some browsers this can cause an updated manifest not to be detected.

Another solution, that I am using, but is not pretty is to rename the appcache file. Then all content will be refreshed as the appcache will be lost.

Related

HTML5, how exactly does appcache work?

so ive got a file-server thats listening on my IP.
I created a test.html, test.js and a manifest.appcache.
My appcache says :
CACHE MANIFEST
CACHE:
test.html
test.js
NETWORK :
*
Meanwhile, my test.html :
<html manifest="manifest.appcache">
If i access on the test.html, everything is working, however if i want to change something in my html file and reload the page, nothing changed(the old html file is cached).
If i change something on my appcache file, for example just edit a space behind the variables and reload my page, it accepts all changes from my html file and is not ignoring the changes anymore.
Why is that?
How can i make it listen to my html file everytime i reload the page?
This is how the cache works. If you want to refresh the cache as you already said you need to change your manifest file.
You must modify the manifest file itself to inform the browser to refresh cached files.
But you can use JS to check if the cache is changed.
You can get the cache object like this: window.applicationCache
window.addEventListener('load', function(e) {
// Add an event listener to the cache
window.applicationCache
.addEventListener('updateready', function(e) {
// Check if ready to update (The update ready status is 4)
if (
window.applicationCache.status ==
window.applicationCache.UPDATEREADY) {
// Get new app chache
// window.location.reload();
window.applicationCache.swapCache()
}
}, false);
}, false);
Check the official docs here: https://html.spec.whatwg.org/#applicationcache
Please note this feature is deprecated an you shouldn't use it
From MDN:
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
What should I do?
You should be using the new Service Worker API, it is a direct replacement for the Application cache. Service workers have all the features off App Cache and even more.
For Service Worker API check these:
MDN
Google Dev
W3C (Github)

HTML5 App Cache: Manifest ist updated but files are taken from appcache one more time

I have a cache manifest with a comment in it
# Version 3.2
in order to update all the App I simply change the Version number. It works, but:
When I update the manifest, everything is updated correctly (new cache is filled) but the actual files are taken ONE more time from the (old) cache. when I reload twice everything is updated. Is this behaviour correct? Using chrome 21.
Thanks
Yes, this is the current "correct" behaviour. This is what happens:
When you just made changes to the manifest file, and you refresh the browser, this is what happens (assuming you're online)
the browser first loads back all the files in the cache
then the browser check online for your manifest file
it detects that the manifest file has changed, it will then proceed to download the new files
however, keep in mind, at this time, you will still be looking at your 'old files' because the browser has loaded the old files before going online to download the 'new files'
if at this point, if you hit refresh again (2nd time), you should get the 'new files'
This is currently the standard behaviour. Some people put some event handlers to prompt the user to do another refresh (after the 1st refresh)
Personally, I think the browser should be responsible to alert the user to make another refresh after finish downloading the new files, but right now, most people put in event handlers from the "window.applicationCache" to fire events to help manage this.
To look at an example of using window.applicationCache, go here : http://www.html5rocks.com/en/tutorials/appcache/beginner/
it's under the "Updating the Cache" section.
It is possible to instantly swap the cache as described here:
function updateSite(event) {
window.applicationCache.swapCache();
}
window.applicationCache.addEventListener('updateready', updateSite, false);

HTML5 browsers hanging on to cached manifest file

I'm using HTML5 appcache and mostly it's working well. However, sometimes, users' browsers (Chrome or Safari) will hold onto the cached manifest file even though I'm positive that the server has a brand new manifest file with a unique version number inside of a comment (like with "# app version 1.0.0.8" or whatever).
In IIS (version 6), the content expiration was set to 1 day, so could that be the problem? I can't seem to reproduce this issue which makes debugging difficult. As a precaution, in IIS I've changed the content expiration to "expire immediately" for the directory that stores the manifest file. Could that explain why some browsers were hanging onto manifest files even when a new version was available?
I also noticed that when a browser was behaving this way, even if I deleted the manifest file on the server, the user's browser would use its own cached copy of the manifest file which isn't supposed to happen if the file is no longer available in my understanding.
Thanks,
Andy
Taken from my answer here : https://stackoverflow.com/a/13282735/727575
Yes, this is the current "correct" behaviour. It has nothing to do with IIS content expiration. This is what happens:
When you just made changes to the manifest file, and you refresh the browser, this is what happens (assuming you're online)
the browser first loads back all the files in the cache
then the browser check online for your manifest file
it detects that the manifest file has changed, it will then proceed to download the new files
however, keep in mind, at this time, you will still be looking at your 'old files' because the browser has loaded the old files before going online to download the 'new files'
if at this point, if you hit refresh again (2nd time), you should get the 'new files'
This is currently the standard behaviour. Some people put some event handlers to prompt the user to do another refresh (after the 1st refresh)
So basically, you need to refresh twice or throw one of the event from 'window.applicationCache' to handle it
To look at an example of using window.applicationCache, go here : http://www.html5rocks.com/en/tutorials/appcache/beginner/
it's under the "Updating the Cache" section.

HTML5 offline "Application Cache Error event: Manifest fetch failed (-1)"

I'm trying to write an HTML5 offline application but can't seem to get Chrome to accept the cache manifest file.
Chrome logs the following output to its console while loading the application:
Creating Application Cache with manifest http://localhost/cache.manifest
Application Cache Checking event
Application Cache Error event: Manifest fetch failed (-1) http://localhost/cache.manifest
However, if I remove all lines from the manifest file except for the first line (i.e. "CACHE MANIFEST") Chrome accepts the manifest:
Creating Application Cache with manifest http://localhost/cache.manifest
Application Cache Checking event
Application Cache Downloading event
Application Cache Progress event (0 of 0)
Application Cache Cached event
But, as soon as I add a new line to the manifest (even if that next line is empty) Chrome reverts to complaining that the fetch failed.
All files are being served locally from a Windows 7 PC via Python using SimpleHTTPServer on port 80. I've updated the types_map in %PYTHON%/Lib/mimetypes.py with the following line:
'.manifest': 'text/cache-manifest',
The manifest should contain the following:
CACHE MANIFEST
scripts/africa.js
scripts/main.js
scripts/offline.js
scripts/libs/raphael-min.js
favicon.ico
apple-touch-icon.png
To cache a website offline (HTML5) you need to specify all the files needed for it to run. In short specify the site main components needed.
Easy way to create a manifest is in Note Pad.
Note: CACHE MANIFEST needs to be first line and your files will follow after a line space as follows:
CACHE MANIFEST
Scripts/script.js
Content/Site.css
Scripts/jquery-ui-1.8.20.min.js
Scripts/modernizr-2.5.3.js
SESOL.png
Scripts/jquery.formatCurrency-1.4.0.min.js
http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css
http://code.jquery.com/jquery-1.8.2.min.js
http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js
Content/themes/images/icons-18-white.png
Controllers/AccountController
Controllers/HomeController
Models/AccountModels
Account/Login
Home/CheckOut
Note2: remove all spaces after each line.
Note:3 you need to follow the exact format FOLDER/File or FOLDER/FOLDER/FILE ect....
Just because you have a manifest file doesnt mean it will load. you need to add the following to the Tag:
<html manifest="~/cache.manifest" type="text/cache-manifest">
Don't forget that after you add this it's cached the first time the page loads. So you need to register a cache event in the 'mobileinit' event.
$(document).on("mobileinit", function () {
//register event to cache site for offline use
cache = window.applicationCache;
cache.addEventListener('updateready', cacheUpdatereadyListener, false);
cache.addEventListener('error', cacheErrorListener, false);
function cacheUpdatereadyListener (){
window.applicationCache.update();
window.applicationCache.swapCache();
}
function cacheErrorListener() {
alert('site not availble offline')
}
}
Download Safari and use the web inspector to find errors.
http://developer.apple.com/library/safari/#documentation/appleapplications/Conceptual/Safari_Developer_Guide/1Introduction/Introduction.html#//apple_ref/doc/uid/TP40007874-CH1-SW1
Tip: Chrome's developer tools "F12" will show you the errors in the manifest load. ie the files you still need to add.
Hope this helps, covers the entire process. I assuming if you are at this stage in development you new to add these to the mobile init:
$.mobile.allowCrossDomainPages = true; // cross domain page loading
$.mobile.phonegapNavigationEnabled = true; //Android enabled mobile
$.mobile.page.prototype.options.domCache = true; //page caching prefech rendering
$.support.touchOverflow = true; //Android enhanced scrolling
$.mobile.touchOverflowEnabled = true; // enhanced scrolling transition availible in iOS 5
Safari Developer Guide:
https://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/Client-SideStorage/Client-SideStorage.html#//apple_ref/doc/uid/TP40002051-CH4-SW4
Have you tried anything like https://manifest-validator.appspot.com/ to validate your manifest?
I've struggled with my manifest file for quite a while, it is really hard to pinpoint what is wrong. Could be something as simple as wrong encoding to an extra line break at the start.
Today I experienced exactly the same problem. After hours of working I came the the key point: the format of manifest file. In short, the file must begin a new line ONLY with ascii(0A), not ascii(0D), or ascii(0D + 0A). Only in this way can I live with Chrome, or I will get a blank page, and the error info in the console window.
According to w3c, (http://www.w3.org/TR/html5/offline.html), in “5.6.3.2 Writing cache manifests”,both 0A, 0D and 0D + 0A are all acceptable. So, my opinion is: Chrome is not compatible with w3c in the point.
Further more, say, if myapp.js is to be cached, it MUST follow the same rule: begins a new line only with ascii(0A), or Chrome will throw the same info in the console windows.
My Chrome is 13.0.782.107
I have now resolved this issue by switching to CherryPy for serving these files :)
If anyone else becomes similarly stuck but wants to keep the server part simple, the following Python may be sufficient for getting started:
import cherrypy
class SimpleStaticServer:
#cherrypy.expose
def index(self):
return '<html><body>Go to the static index page</body></html>'
cherrypy.config.update({
# global
'server.socket_host': '192.168.0.3',
'server.socket_port': 80,
# /static
'tools.staticdir.on': True,
'tools.staticdir.dir': "(directory where static files are stored)",
})
cherrypy.quickstart(SimpleStaticServer())
If you want to visit the "site" from another device, you'll need to use the external IP address (for me this was 192.168.0.3). Otherwise, you can just use '127.0.0.1' for the 'server.socket_host' value. I then point my browser to http://192.168.0.3/index.html to get my static index page.
I have resolved this issue in visual studio for MVC application.
follow below steps:
I have created .appcache file in notepad and copy manifest file content into it.
(you don't need to create .Manifest file OR not create Manifest.cshtml view. just create .appcache file in notepad.)
give reference as
<html manifest="~/example.appcache"> in view
and issue will be resolved
I think the line
CACHE:
is missing in the manifest file (should be the 2nd line, before the list of files.

Force browser to clear cache

Is there a way I can put some code on my page so when someone visits a site, it clears the browser cache, so they can view the changes?
Languages used: ASP.NET, VB.NET, and of course HTML, CSS, and jQuery.
If this is about .css and .js changes, then one way is "cache busting" by appending something like "_versionNo" to the file name for each release. For example:
script_1.0.css // This is the URL for release 1.0
script_1.1.css // This is the URL for release 1.1
script_1.2.css // etc.
or after the file name:
script.css?v=1.0 // This is the URL for release 1.0
script.css?v=1.1 // This is the URL for release 1.1
script.css?v=1.2 // etc.
You can check this link to see how it could work.
Look into the cache-control and the expires META Tag.
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="EXPIRES" CONTENT="Mon, 22 Jul 2002 11:12:01 GMT">
Another common practices is to append constantly-changing strings to the end of the requested files. For instance:
<script type="text/javascript" src="main.js?v=12392823"></script>
Update 2012
This is an old question but I think it needs a more up to date answer because now there is a way to have more control of website caching.
In Offline Web Applications (which is really any HTML5 website) applicationCache.swapCache() can be used to update the cached version of your website without the need for manually reloading the page.
This is a code example from the Beginner's Guide to Using the Application Cache on HTML5 Rocks explaining how to update users to the newest version of your site:
// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new hotness.
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {
// Manifest didn't changed. Nothing new to server.
}
}, false);
}, false);
See also Using the application cache on Mozilla Developer Network for more info.
Update 2016
Things change quickly on the Web.
This question was asked in 2009 and in 2012 I posted an update about a new way to handle the problem described in the question. Another 4 years passed and now it seems that it is already deprecated. Thanks to cgaldiolo for pointing it out in the comments.
Currently, as of July 2016, the HTML Standard, Section 7.9, Offline Web applications includes a deprecation warning:
This feature is in the process of being removed from the Web platform.
(This is a long process that takes many years.) Using any of the
offline Web application features at this time is highly discouraged.
Use service workers instead.
So does Using the application cache on Mozilla Developer Network that I referenced in 2012:
Deprecated This feature has been removed from the Web standards.
Though some browsers may still support it, it is in the process of
being dropped. Do not use it in old or new projects. Pages or Web apps
using it may break at any time.
See also Bug 1204581 - Add a deprecation notice for AppCache if service worker fetch interception is enabled.
Not as such. One method is to send the appropriate headers when delivering content to force the browser to reload:
Making sure a web page is not cached, across all browsers.
If your search for "cache header" or something similar here on SO, you'll find ASP.NET specific examples.
Another, less clean but sometimes only way if you can't control the headers on server side, is adding a random GET parameter to the resource that is being called:
myimage.gif?random=1923849839
I had similiar problem and this is how I solved it:
In index.html file I've added manifest:
<html manifest="cache.manifest">
In <head> section included script updating the cache:
<script type="text/javascript" src="update_cache.js"></script>
In <body> section I've inserted onload function:
<body onload="checkForUpdate()">
In cache.manifest I've put all files I want to cache. It is important now that it works in my case (Apache) just by updating each time the "version" comment. It is also an option to name files with "?ver=001" or something at the end of name but it's not needed. Changing just # version 1.01 triggers cache update event.
CACHE MANIFEST
# version 1.01
style.css
imgs/logo.png
#all other files
It's important to include 1., 2. and 3. points only in index.html. Otherwise
GET http://foo.bar/resource.ext net::ERR_FAILED
occurs because every "child" file tries to cache the page while the page is already cached.
In update_cache.js file I've put this code:
function checkForUpdate()
{
if (window.applicationCache != undefined && window.applicationCache != null)
{
window.applicationCache.addEventListener('updateready', updateApplication);
}
}
function updateApplication(event)
{
if (window.applicationCache.status != 4) return;
window.applicationCache.removeEventListener('updateready', updateApplication);
window.applicationCache.swapCache();
window.location.reload();
}
Now you just change files and in manifest you have to update version comment. Now visiting index.html page will update the cache.
The parts of solution aren't mine but I've found them through internet and put together so that it works.
For static resources right caching would be to use query parameters with value of each deployment or file version. This will have effect of clearing cache after each deployment.
/Content/css/Site.css?version={FileVersionNumber}
Here is ASP.NET MVC example.
<link href="#Url.Content("~/Content/Css/Reset.css")?version=#this.GetType().Assembly.GetName().Version" rel="stylesheet" type="text/css" />
Don't forget to update assembly version.
I had a case where I would take photos of clients online and would need to update the div if a photo is changed. Browser was still showing the old photo. So I used the hack of calling a random GET variable, which would be unique every time. Here it is if it could help anybody
<img src="/photos/userid_73.jpg?random=<?php echo rand() ?>" ...
EDIT
As pointed out by others, following is much more efficient solution since it will reload images only when they are changed, identifying this change by the file size:
<img src="/photos/userid_73.jpg?modified=<? filemtime("/photos/userid_73.jpg")?>"
A lot of answers are missing the point - most developers are well aware that turning off the cache is inefficient. However, there are many common circumstances where efficiency is unimportant and default cache behavior is badly broken.
These include nested, iterative script testing (the big one!) and broken third party software workarounds. None of the solutions given here are adequate to address such common scenarios. Most web browsers are far too aggressive caching and provide no sensible means to avoid these problems.
Updating the URL to the following works for me:
/custom.js?id=1
By adding a unique number after ?id= and incrementing it for new changes, users do not have to press CTRL + F5 to refresh the cache. Alternatively, you can append hash or string version of the current time or Epoch after ?id=
Something like ?id=1520606295
<meta http-equiv="pragma" content="no-cache" />
Also see https://stackoverflow.com/questions/126772/how-to-force-a-web-browser-not-to-cache-images
Here is the MDSN page on setting caching in ASP.NET.
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60))
Response.Cache.SetCacheability(HttpCacheability.Public)
Response.Cache.SetValidUntilExpires(False)
Response.Cache.VaryByParams("Category") = True
If Response.Cache.VaryByParams("Category") Then
'...
End If
Not sure if that might really help you but that's how caching should work on any browser. When the browser request a file, it should always send a request to the server unless there is a "offline" mode. The server will read some parameters like date modified or etags.
The server will return a 304 error response for NOT MODIFIED and the browser will have to use its cache. If the etag doesn't validate on server side or the modified date is below the current modified date, the server should return the new content with the new modified date or etags or both.
If there is no caching data sent to the browser, I guess the behavior is undetermined, the browser may or may not cache file that don't tell how they are cached. If you set caching parameters in the response it will cache your files correctly and the server then may choose to return a 304 error, or the new content.
This is how it should be done. Using random params or version number in urls is more like a hack than anything.
http://www.checkupdown.com/status/E304.html
http://en.wikipedia.org/wiki/HTTP_ETag
http://www.xpertdeveloper.com/2011/03/last-modified-header-vs-expire-header-vs-etag/
After reading I saw that there is also a expire date. If you have problem, it might be that you have a expire date set up. In other words, when the browser will cache your file, since it has a expiry date, it shouldn't have to request it again before that date. In other words, it will never ask the file to the server and will never receive a 304 not modified. It will simply use the cache until the expiry date is reached or cache is cleared.
So that is my guess, you have some sort of expiry date and you should use last-modified etags or a mix of it all and make sure that there is no expire date.
If people tends to refresh a lot and the file doesn't get changed a lot, then it might be wise to set a big expiry date.
My 2 cents!
I implemented this simple solution that works for me (not yet on production environment):
function verificarNovaVersio() {
var sVersio = localStorage['gcf_versio'+ location.pathname] || 'v00.0.0000';
$.ajax({
url: "./versio.txt"
, dataType: 'text'
, cache: false
, contentType: false
, processData: false
, type: 'post'
}).done(function(sVersioFitxer) {
console.log('Versió App: '+ sVersioFitxer +', Versió Caché: '+ sVersio);
if (sVersio < (sVersioFitxer || 'v00.0.0000')) {
localStorage['gcf_versio'+ location.pathname] = sVersioFitxer;
location.reload(true);
}
});
}
I've a little file located where the html are:
"versio.txt":
v00.5.0014
This function is called in all of my pages, so when loading it checks if the localStorage's version value is lower than the current version and does a
location.reload(true);
...to force reload from server instead from cache.
(obviously, instead of localStorage you can use cookies or other persistent client storage)
I opted for this solution for its simplicity, because only mantaining a single file "versio.txt" will force the full site to reload.
The queryString method is hard to implement and is also cached (if you change from v1.1 to a previous version will load from cache, then it means that the cache is not flushed, keeping all previous versions at cache).
I'm a little newbie and I'd apreciate your professional check & review to ensure my method is a good approach.
Hope it helps.
In addition to setting Cache-control: no-cache, you should also set the Expires header to -1 if you would like the local copy to be refreshed each time (some versions of IE seem to require this).
See HTTP Cache - check with the server, always sending If-Modified-Since
There is one trick that can be used.The trick is to append a parameter/string to the file name in the script tag and change it when you file changes.
<script src="myfile.js?version=1.0.0"></script>
The browser interprets the whole string as the file path even though what comes after the "?" are parameters. So wat happens now is that next time when you update your file just change the number in the script tag on your website (Example <script src="myfile.js?version=1.0.1"></script>) and each users browser will see the file has changed and grab a new copy.
Force browsers to clear cache or reload correct data? I have tried most of the solutions described in stackoverflow, some work, but after a little while, it does cache eventually and display the previous loaded script or file. Is there another way that would clear the cache (css, js, etc) and actually work on all browsers?
I found so far that specific resources can be reloaded individually if you change the date and time on your files on the server. "Clearing cache" is not as easy as it should be. Instead of clearing cache on my browsers, I realized that "touching" the server files cached will actually change the date and time of the source file cached on the server (Tested on Edge, Chrome and Firefox) and most browsers will automatically download the most current fresh copy of whats on your server (code, graphics any multimedia too). I suggest you just copy the most current scripts on the server and "do the touch thing" solution before your program runs, so it will change the date of all your problem files to a most current date and time, then it downloads a fresh copy to your browser:
<?php
touch('/www/sample/file1.css');
touch('/www/sample/file2.js');
?>
then ... the rest of your program...
It took me some time to resolve this issue (as many browsers act differently to different commands, but they all check time of files and compare to your downloaded copy in your browser, if different date and time, will do the refresh), If you can't go the supposed right way, there is always another usable and better solution to it. Best Regards and happy camping. By the way touch(); or alternatives work in many programming languages inclusive in javascript bash sh php and you can include or call them in html.
For webpack users:-
I added time with chunkhash in my webpack config. This solved my problem of invalidating cache on each deployment. Also we need to take care that index.html/ asset.manifest is not cached both in your CDN or browser. Config of chunk name in webpack config will look like this:-
fileName: [chunkhash]-${Date.now()}.js
or If you are using contenthash then
fileName: [contenthash]-${Date.now()}.js
This is the simple solution I used to solve in one of my applications using PHP.
All JS and CSS files are placed in a folder with version name. Example : "1.0.01"
root\1.0.01\JS
root\1.0.01\CSS
Created a Helper and Defined the version Number there
<?php
function system_version()
{
return '1.0.07';
}
And Linked JS and SCC Files like below
<script src="<?= base_url(); ?>/<?= system_version();?>/js/generators.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<?= base_url(); ?>/<?= system_version(); ?>/css/view-checklist.css" />
Whenever I make changes to any JS or CSS file, I change the System Verson in Helper and rename the folder and deploy it.
I had the same problem, all i did was change the file names which are linked to my index.html file and then went into the index.html file and updated their names, not the best practice but if it works it works. The browser sees them as new files so they get redownloaded on to the users device.
example:
I want to update a css file, its named styles.css, change it to styless.css
Go into index.html and update , and change it to
in case interested I've found my solution to get browsers refreshing .css and .js in the context of .NET MVC (.net fw 4.8) and the use of bundles.
I wanted to make browsers refresh cached files only after a new assembly is deployed.
Buinding on Paulius Zaliaduonis response, my solution is as follows:
store your application base url in the web config app settings (the HttpContext is not yet available at runtime during the RegisterBundle...), then make this parameter changing according to the configuration (debug, staging, release...) by the xml transform
In BundleConfig RegisterBundles get the assembly version by the means of reflection, and...
...change the default tag format of both styles and scripts so that the bundling system generates link and script tags appending a query string parameter on them.
Here is the code
public static void RegisterBundles(BundleCollection bundles)
{
string baseUrl = system.Configuration.ConfigurationManager.AppSettings["by.app.base.url"].ToString();
string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
Styles.DefaultTagFormat = $"<link href='{baseUrl}{{0}}?v={assemblyVersion}' rel='stylesheet'/>";
Scripts.DefaultTagFormat = $"<script src='{baseUrl}{{0}}?v={assemblyVersion}'></script>";
}
You'll get tags like
<script src="https://example.org/myscriptfilepath/script.js?v={myassemblyversion}"></script>
you just need to remember to to build a new version before deploying.
Ciao
2023 onward
At the time of writing, many web browsers support the Clear-Site-Data HTTP header [MDN reference]. To instruct the client web browser to clear the cache for the website domain and subdomains, set the following header in the HTTP response from the server:
Clear-Site-Data: "cache"
Alternatively, the following header may be better supported across browsers, but it clears other website data, such as localStorage and cookies, in addition to the cache.
Clear-Site-Data: "*"
However note that intermediate caches (e.g. a CDN) may not understand or respect this header, so intermediate caches may still respond with previously cached data.
Do you want to clear the cache, or just make sure your current (changed?) page is not cached?
If the latter, it should be as simple as
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">