Answer the question
In order to leave comments, you need to log in
js/css caching bypass
Hello! I want to ask a very simple question:
There is a self-written site, which is also constantly being finalized, hence the script and style files are being finalized.
Modern browsers are very good at caching downloaded files on their own, and when the file on the server changes, they stubbornly continue to use what is in the cache.
How can I force the browser to download a file from the server again each time? I would like to see the most cross-browser solution.
For now, we are saving ourselves by manually renaming files before each update, but I really don’t want to continue doing this ...
Perhaps there is some more automated way to prescribe the script version in both the file name and template headers?
Answer the question
In order to leave comments, you need to log in
The easiest option for you, in my opinion, is, of course, to use the GET parameter after the script:
<script src="/js/script.js?1273455236"></script>
main.js?123
main.css?123
If parameters (?123) are passed to a file, the browser must load it again.
Isn't it better to get out of your head all these anachronisms (al even insanity) described above, and use what was actually implemented for your task, that is, ETag. Read more on Wikipedia, or somewhere else (there is a lot of information).
+ that everything happens automatically and the file is cached.
Usage example for ".htaccess":
# Set ETag to last modified time and file size
FileETag MTime Size
for nginx something like this
location ~* /static/\d+/ { alias /path/to/static; }
<script src="/static/123/js/core.js"></script>
if you need to disable caching for some file at all, then in the template add the unixtime (time in seconds since the unix epoch) to the end of the file
style.css?1292227150
In Ruby, this is Time.now.to_i, there are similar functions in almost all languages.
There is a constant, for example, REVISION which is equal to the current revision number of the static.
All statics are included as /css/REVISION/main.css, /js/REVISION/core.css
In nginx it is written as above:
<script src="js/jquery.canvasjs.min.js?v=<?php echo filectime('js/jquery.canvasjs.min.js'); ?>"></script>
If you need to disable caching altogether, then in my opinion the most reliable way is to generate a random number as described above and add the Cache-Control: no-cache, no-store header to the server response.
Because there is no implementation technology in the question, then I’ll write how with this in django. For django, there are about a dozen libraries that do this: djangopackages.com/grids/g/asset-managers/
After the initial setup, everything works automatically: the file has changed => on the server, the static is rebuilt, recompressed, a new unixtime is attributed to the collected file and in html the path is updated.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question