If you have or are working with various JavaScript files, you might have faced the same problems we have faced over the last few weeks, those of .js and .css files increasing the loading time of your website, and the constant irritation of minifying all those .js files. So, here are two steps which can solve both these problems:
Reducing the size of JS files
Use the JSMin filter, which removes comments and unnecessary whitespace from JavaScript files. It typically reduces file size by half, resulting in faster downloads. You can get this library at JSMin Library.
Reducing the number of JS and CSS files
At the point of loading all your .js and .css files, create an array containing the paths to all the .js and .css files. This would ideally be done in your controller. See example below:
$this->data['js'] = array(’sample1.js’,’sample2.js’,’sample3.js’);
$this->data['css'] = array(’sample1.css’,’sample2.css’,’sample3.css’);
Then at the point of calling your .js and .css files, simply call the following function. This would ideally be done in your view file.
<script src="<?=merge_resources($js,";",".js",true)?>" type="text/javascript"></script>
<link href="<?=merge_resources($css,"n",".css",false)?>" rel="stylesheet" type="text/css">
This merge_resources function hashes the modified time of all your .js or .css files and stores a minified version with the name of the hash value. At any future call, it checks if a the hash values match, in which case it does not create a new minified file, else it creates and returns the new minified file. Here is an implementation…
function merge_resources($res_array,$delim=”,$ext=”,$jsmin=false)
{
$jsmin=false;
if(count($res_array))
{
$files = array();
foreach($res_array as $r)
{
$files[$r]=filemtime( //insert path to the file $r );
}
$md5 = md5(serialize($files));
$outpath = "//insert the path you want/$md5".$ext;
$outfile = $_SERVER['DOCUMENT_ROOT'].$outpath;
if(!file_exists($outfile))
{
ob_start();
foreach($res_array as $r)
{
include //insert path to the file $r;
echo $delim;
}
$resdata = ob_get_clean();
if($jsmin)
{
include_once ‘JSMin.php’;
$resdata = JSMin::minify($resdata);
}
file_put_contents($outfile,$resdata);
}
return $outpath;
}
}