![]() |
|
Snippets |
|
Hi!
I am using a lot of hand written jscript codes due to the required behavior not found in any javascript framework. I've created my Objects in distinct files, although some of them are quite small ( <1kb ). So to make it fast, I've written a filter class that actually parses the files found in the /js directories having *.js suffix. It does not only parse them together but removes whitespaces, comments, indentations so the sum filesize gets a bit compressed. The filter also includes the final file into the response so there is no need to include any *.js ( inside /js ) in a template.
<?php class JavascriptParser extends sfFilter { public function execute($filterChain) { $filterChain->execute(); $fp = fopen( "js/compiled.js", "w" ); JavascriptParser::getJSFiles( "js", $fp ); fclose ( $fp ); $response = $this->getContext()->getResponse(); $content = $response->getContent(); if (false !== ($pos = strpos($content, '</head>'))) { $html = "<script type='text/javascript' src='/js/compiled.js'></script>"; if ($html) { $response->setContent(substr($content, 0, $pos).$html.substr($content, $pos)); } } } public function getJSFiles( $dir, &$fp ) { $hDir = opendir( $dir ); while( ( $filename = readdir( $hDir ) ) !== false ) { if ( is_dir( $filename ) ) { } else if ( is_dir( $dir."/".$filename ) ) JavascriptParser::getJSFiles( $dir."/".$filename, $fp ); else if ( strpos( $filename, ".js" ) !== false && $filename != "compiled.js" ) { $tmpFile = fopen( $dir."/".$filename, "r" ); $data = fread( $tmpFile, filesize( $dir."/".$filename ) ); $data = preg_replace( "'\/\*.*?\*\/'si", "", $data ); $data = preg_replace( "'//.*?\n'si", "", $data ); $data = preg_replace( "'[ \t]+'", " ", $data ); fwrite( $fp, " \n".$data ); fclose( $tmpFile ); } } closedir( $hDir ); } } ?>
The same should be done with *.css files, since they are even smaller and loading many small files takes much more time then loading one big.
Best Regards