Skip to content

Instantly share code, notes, and snippets.

@mailightkun
Forked from ckenney108/js-combine-and-version.php
Last active August 29, 2015 14:12
Show Gist options
  • Save mailightkun/7c1f4e56d035191b53c3 to your computer and use it in GitHub Desktop.
Save mailightkun/7c1f4e56d035191b53c3 to your computer and use it in GitHub Desktop.
<?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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment