Compressing included javascript files
I have been hard at work on Nanobyte, trying to get it ready for Alpha status. I recently worked out file compression to make the pages load faster, and thought I would share.
When I built Nanobyte, I wrote a function to include JS and CSS files with a function that adds each filename to an array for inclusion. With this array, I can combine all of the files into one large file and compress it for viewing.
- public static function CompressFiles($fileArray,$type){
- if($type != 'css'){
- $ob = "<?php
- ob_start (\"ob_gzhandler\");
- ?>\n";
- }else{
- $ob = "<?php
- ob_start(\"ob_gzhandler\");
- header(\"Content-type: text/css; charset: UTF-8\");
- header(\"Cache-Control: must-revalidate\");
- ?>";
- }
- $filename = './templates/'.THEME_PATH.'/'.$type.'/compressed.php';
- $fh = fopen($filename, 'w');
- fwrite($fh, $ob);
- foreach($fileArray as $file){
- $contents = file_get_contents($file);
- fwrite($fh, $contents);
- }
- fclose($fh);
- return $filename;
- }
This function does several things.
First, we set the output buffer and headers to add to the new file.
We then tell the function where the file is going to be created, and open it for writing.
Once it is open, we write our PHP code block to the file. To get this to work correctly, the file must have a .php extension.
Next, we read the contents of every included file one by one, and append them to our new file. This makes for one large conglomerated file to include.
After all files have been added, we close the file and return the filename of the new file to be included.
Since the page is a php file, the code block will run, which uses ob_gzhandler to compress the file. Using this on Nanobyte, I have reduced a 420KB total page size down to 168KB.
A side effect of this process is that we also reduce the amount of server requests tht our server hs to process. Overall, I gained just over 3 full seconds for the page to load. before this function, the average load time was 6.2 seconds, we are down to 3.19. Incredible!
One last note: Though the file is a .php file, it CAN be included like a regular JS file.. e.g.
<script type="text/javascript" src="/js/compressed.php"></script>

hifvxjmSqwEEw
, buying viagra online, xanax without prescription, buy ultram, xanax and grapefruit, tramadol, cheap cialis,
yiljMWYboLWthNvgG
homeowners insurance gnwvrs auto insurance 093 car insurance %] slots online 301