Created
July 22, 2013 13:10
-
-
Save jboonstra/6053701 to your computer and use it in GitHub Desktop.
cache-busting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// assumes SITE_VERSION, BASEPATH constants are set; assumes CodeIgniter configuration | |
function buster($url) { | |
if (!($url && is_scalar($url))) { | |
return ''; | |
} | |
// trim off any leading '/' in the URL; we'll re-add it later | |
$url = ltrim($url, '/'); | |
$parts = explode('.', $url); | |
$ext = array_pop($parts); | |
// should we bust cache at all? | |
if (get_instance()->config->item('bust-cache')) { | |
// last-modified time on dev sites | |
if (SITE_VERSION == 'vDEV') { | |
$file = realpath(BASEPATH . '../../public/' . $url); | |
if (is_readable($file)) { | |
$parts[] = 'v0.0.' . filemtime($file); | |
} | |
} | |
// deployed version on the live site | |
else { | |
$parts[] = SITE_VERSION; | |
} | |
} | |
// rebuild a valid URL | |
$parts[] = $ext; | |
return '/' . join('.', array_filter($parts)); | |
} | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- with cache-busting completely disabled --> | |
<script src="/javascripts/somefile.js"></script> | |
<!-- with cache-busting enabled, in dev mode - always refresh --> | |
<script src="/javascripts/somefile.v0.0.1374498234.js"></script> | |
<!-- with cache-busting enabled, in production mode; use deployed version tag --> | |
<script src="/javascripts/somefile.v1.2.3.js"></script> | |
<!-- with cache-busting enabled, in production mode; rewrite rule also supports git SHA1 version strings --> | |
<script src="/javascripts/somefile.SHA1-52145c.js"></script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Handle requests for CSS/JS/images that specify a version | |
RewriteRule ^(images|css|javascripts)/(.*)\.(?:(?:v[0-9]+\.[0-9]+\.[0-9]+[a-z]?[0-9]*)|(?:SHA1\-[a-zA-Z0-9]+))\.(js|css|png|jpg|gif|ico)$ /$1/$2.$3 [L,NC] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="<?=buster('javascripts/somefile.js')?>"></script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment