If you find my work valuable, please consider sponsoring |
Adds ?v=
to all your CSS/JS and the value of v
is the last git commit hash.
To make search engines happy you need to use very long browser's cache lifetime (with or without a CDN), but if you tell browsers to cache a css or a js for 1 year and then you need to modify it? The browsers won't receive the new version and your website will break.
My solution is to add a v=xxx
parameter to all CSS/JS URLs, this way the cache will be forced to
update and the new version of the files will be stored in cache until the next update.
In order to do that reliably and consistently I've created this module that intercepts the
http_response_send_before event, uses as little preg_regex as possible in order to be as
performant as possible to add the v=xxx
parameter.
This approach should work also with full page cache modules.
How to gen the version number to use in the v=xxx
parameter?
This module supports 2 approaches:
- using the last
Git commit hash
(only the first 6 characters) as the version number - if that fails then a timestamp is used
The git method is preferred because the generated version number won't change unless a new change is pushed on the repository. However, in order to work, OpenMage base dir must also be the Git project root directory and the .git folder has to be present in all servers you need this functionality to work.
Resuming:
- Automatically reads the last Git commit hash, extracts the first 6 characters
- Saves this version number in OpenMage config cache for 1hour (if you flush config cache you also flush this value) in order to have a little impact on the filesystem as possible
- If the git approach doesn't work, the version number because the current timestamp (and gets cached for 24 hours)
- Parsed the output HTML and intercepts all
<script
and<link
tags, extracts the URLs and adds thev=xxx
parameter (using?v
or&v
accordingly) - It only catches
<script
tags withsrc
parameter and<link
tags withhref
parameter but only if the link is of typeicon
orstylesheet
(we must avoid modifying a canonical by mistake)
Limitations:
- You have to have the .git folder in the production server(s) too (be sure to deny HTTP access to .git/* in your .htaccess)
This module is provided "as is" and I'll not be responsible for any problem or damage.
Install via composer (composer require fballiano/openmage-cssjs-versioning
),
modman (modman clone https://github.com/fballiano/openmage-cssjs-versioning
)
or any other way you like
If you have any issues with this extension, open an issue on GitHub.
Any contributions are highly appreciated. The best way to contribute code is to open a pull request on GitHub.
Fabrizio Balliano
http://fabrizioballiano.com
@fballiano
OSL - Open Software Licence 3.0
(c) Fabrizio Balliano