Skip to content

Instantly share code, notes, and snippets.

@jboonstra
Created July 22, 2013 13:10
Show Gist options
  • Save jboonstra/6053701 to your computer and use it in GitHub Desktop.
Save jboonstra/6053701 to your computer and use it in GitHub Desktop.
cache-busting
<?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));
}
?>
<!-- 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>
# 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]
<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