Skip to content

Instantly share code, notes, and snippets.

@ckenney108
Created December 11, 2013 17:19
Show Gist options
  • Save ckenney108/7914608 to your computer and use it in GitHub Desktop.
Save ckenney108/7914608 to your computer and use it in GitHub Desktop.
PHP script for concatenation and versioning of external JavaScript files.
<?php
/**
* Create an associative array of JavaScript files
* and their respective file modification times.
*/
$jsfiles = array(
'first.js' => filemtime('path/to/first.js'),
'second.js' => filemtime('path/to/second.js'),
'third.js' => filemtime('path/to/third.js')
);
/**
* Encode $jsfiles array as JSON and compare to stored JSON file.
*/
$json = file_get_contents('path/to/jsfiles.json');
if(json_encode($jsfiles) !== $json) {
/**
* If $jsfiles array and JSON file don't match,
* that means one or more files have changed.
*
* Update the JSON file with the new values.
*/
file_put_contents('path/to/jsfiles.json', json_encode($jsfiles));
/**
* Combine JS files and place them in a single concatenated file
*/
$js = file_get_contents('path/to/first.js');
$js .= file_get_contents('path/to/second.js');
$js .= file_get_contents('path/to/third.js');
file_put_contents('path/to/concatenated/file.js', $js);
}
/**
* Use the MD5 hash of the concatenated file as a query string.
*
* Query string versioning is not best practice,
* but 60% of the time it works every time.
*/
$concat_hash = hash_file('md5', 'path/to/concatenated/file.js');
?>
<script src="path/to/concatenated/file.js?<?= $concat_hash ?>" async></script>
@ckenney108
Copy link
Author

I also use a minifier (JShrink), but didn't include that code here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment