How to cache/refresh static resources

They're a couple of ways to cache static resources, e.g. css, javascript and images.  You can specify the default cache values in .htaccess file (as shown below in ".htaccess_original"). After some tweaking effort, I managed to integrate this feature into CodeIgniter. The main issue of this solution would be retrieving the last modified date of each file.

Server Side
# Default cache values
ExpiresActive ON
ExpiresByType text/html "access plus 1 minute"
ExpiresByType text/css "access plus 1 day"
ExpiresByType text/javascript "access plus 7 days"
ExpiresByType application/x-javascript "access plus 7 days"
ExpiresByType application/javascript "access plus 7 days"
ExpiresByType application/x-shockwave-flash "access plus 7 days"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/x-icon "access plus 2 months"
# Rules for versioned static files, ignoring the version number
# Example: assets/js/common.13453234.js
RewriteRule ^(.*)(js|css)/(.+)\.(.+)\.(js|css)$ $1/$2/$3.$5 [L]
view raw .htaccess hosted with ❤ by GitHub
<!-- Method 01 A & B -->
<script type="text/javascript" src="<?php echo site_url(autoVer('assets/js/views/schedule.js')); ?>"></script>
<!-- Method 02 -->
<script type="text/javascript" src="<?php echo site_ver_url('assets/js/views/common.js'); ?>"></script>
view raw header.php hosted with ❤ by GitHub
<?php
if ( ! function_exists('autoVer')) {
/**
* Method 01 A:
* Append last modified datetime to filename, .htaccess needs to have the corresponding rule
* E.g. "assets/css/style.css" converts to "assets/css/style.1363054031.css"
* @param $url String Relative path
* @return String Modified relative path
*/
function autoVer($url){
$path = pathinfo($url);
$ver = '.' . filemtime($_SERVER['DOCUMENT_ROOT'] . $url) . '.';
return $path['dirname'].'/'.str_replace('.', $ver, $path['basename']);
}
/**
* Method 01 B:
* If your Codeigniter has branch name, e.g. http://www.example.com/dev/assets/css/style.css
* There'll be an extra step to retrieve the branch name
* @param $url String Relative path
* @return String Modified relative path
*/
function autoVer($url){
$CI =& get_instance();
// Get branch name from base_url config, remove any '/' characters
$parts = parse_url($CI->config->item('base_url'));
$branch = strtok($parts['path'], '//');
// Build new file path with version number attached
$path = pathinfo($url);
$ver = '.' . filemtime($_SERVER['DOCUMENT_ROOT'] . $branch . '/' . $url) . '.';
return $path['dirname'].'/'.str_replace('.', $ver, $path['basename']);
}
}
/**
* Method 02:
* Integrate auto-versioning to site_url() of CodeIgniter, cleaner code
* Supports branch name
*/
if ( ! function_exists('site_ver_url')) {
function site_ver_url($url) {
$CI =& get_instance();
// Get branch name, remove any '/' characters
$parts = parse_url($CI->config->item('base_url'));
$branch = strtok($parts['path'], '//');
// Build new file path with version number attached
$path = pathinfo($url);
$ver = '.' . filemtime($_SERVER['DOCUMENT_ROOT'] . $branch . '/' . $url) . '.';
return site_url($path['dirname'].'/'.str_replace('.', $ver, $path['basename']));
}
}
Server & Client sides
If there're css or javascript files that you need to load dynamically, then you would need to use another approach. For CodeIgniter, I set a config item, called "code_revision" which store the latest version number of your source project. PHP and Javascript will be referring to this variable for consistency.
// Similar functionalities, same name as its PHP counterpart, located in Nest_url_helper.php
// @param url String: relative path of the source
function site_ver_url(url) {
if(baseURL === undefined || baseURL == '') {
return;
}
if(codeRevision === undefined) {
codeRevision = 100;
}
// retrieve filename
var filename = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
// retrieve file extension
var fileExt = url.split('.').pop();
// replace filename
return (baseURL + url.replace(filename, filename + '.' + codeRevision));
}
view raw common.js hosted with ❤ by GitHub
/*
|--------------------------------------------------------------------------
| Code Revision
|--------------------------------------------------------------------------
|
| This version number will be altered when the branch source code is updated.
| Make sure there is so special or space characters in between, else PHP and
| Javascript will have different values
| E.g. "62+ p.67" in PHP will be "62+%20p.67" in JS
|
*/
$config['code_revision'] = '62+p.67-100';
view raw config.php hosted with ❤ by GitHub
<script type="text/javascript">
// this global variable will be used in common.js
var codeRevision = '<?php echo $this->config->item('code_revision'); ?>';
</script>
<script type="text/javascript" src="<?= site_ver_url('assets/js/views/schedule.js'); ?>"></script>
view raw header.php hosted with ❤ by GitHub
<?php
/**
* Auto-versioning. Append last modified datetime to filename, .htaccess needs to have the corresponding rule
* Similar function, same name in javascript, common.js
* E.g. "assets/css/style.css" converts to "assets/css/style.1363054031.css"
* @param $url String Relative path
* @return String Modified relative path
*/
if ( ! function_exists('site_ver_url')) {
function site_ver_url($url) {
$CI =& get_instance();
// Get branch name, remove any '/' characters
$parts = parse_url($CI->config->item('base_url'));
$branch = strtok($parts['path'], '//');
// Build new file path with version number attached
$path = pathinfo($url);
$ver = '.' . $CI->config->item('code_revision') . '.';
return site_url($path['dirname'] . '/' . str_replace('.', $ver, $path['basename']));
}
}
// Load the chosen service config javascript dynamically, 5 secs time limit (YUI2)
YAHOO.util.Get.script(site_ver_url('assets/js/' + module + '.js'), {
onSuccess: formSuccess,
onFailure: formFailure,
onTimeout: formFailure,
timeout: 5000,
});
view raw process.js hosted with ❤ by GitHub
References:

No comments:

Post a Comment