问题
I am a web developer, have worked with PHP and .NET both. having over a year of experience working on web I haven't been able to understand the browser caching features thoroughly, I hope Web Gurus here can help me with it. Questions I have in my mind are:
- How does browser actually caches stuff, does it request for to see if the cached file has changed on the server or not,
- What is the Ideal way for a developer to make use of browser caching to its full, but also to be able to push new changes on the site with no hassle at all. I think if browser somehow caches my CSS and JS and Images, and then just makes a checks for their modification to the server every time, this can sort the issue. but I am not sure how to do it.
回答1:
This blog post may help:
http://blog.httpwatch.com/2007/12/10/two-simple-rules-for-http-caching/
It explains how to use of caching, whilst maintaining the ability to make changes when required.
回答2:
With CSS files a standard "workaround" is to incrementally add a parameter to a link:
<link rel="stylesheet" href="http://mysite.com/styles.css?v=1">
<link rel="stylesheet" href="http://mysite.com/styles.css?v=2">
...
This will force a browser to reload the file.
回答3:
If you are using a server side language, you can force the browser to download the file again.
<script src="script.js?<?= uniqid(); ?>">
<img src="myfile.jpg?<?= uniqid(); ?>">
But cache is good if you want to have a faster site, before you start disabling keep in mind that anything that is cache won't have to be downloaded again.
There is another way you can control what needs to be cached, HTML5 Application Cache, dump your cache logic into the manifest file. So every file in your manifest won't be downloaded again, until the manifest file itself is changed.
Just remember that if you changed something in a JS, CSS, Image file, and you need to push that change to recurrent visitors you need to also update your manifest file. You can add like the publish date that way the browser knows that it's a new manifest and it will download everything again.
来源:https://stackoverflow.com/questions/2689236/how-does-browser-work-with-expiration-headers-cache-control-headers-last-modif