📜 ⬆️ ⬇️

Caching js gzip compression

Cache - temporary data or device for their storage, created to speed up reading / writing. All programmers know this. Accelerating web site loading is an extensive topic, starting with the server and ending with the client. Unfortunately, I did not find more or less suitable solutions for combining and caching js-code, so I wrote my own scheme for my blog, which I will briefly describe ..
There is a “ packer ” compression that removes all formatting characters and renames the names of functions and variables in js and provides so-called minified version of the script. Everyone is very familiar with this by the example of large jQuery, TinyMCE, prototype libraries. Besides the fact that the code becomes completely unreadable, it can cause the inoperability of the code when the variable names are dynamic.
My idea is simple - developers need to divide js / css by files to maintain a modular structure. Usually I create a list of files in the controller that need to be attached to this document, instead of manually registering it in the template. But now we need to make it so that before the template is displayed, the caching function is called, which would go through the list, check local files from them for the duration of the change, merge into one file and create or rewrite a gz file with the name formed from md5-hash names of incoming files.
Everything is simple and in total it took 4 hours to think. I give the cache_js method from the Controller class.

 function cache_js(){ $arrNewJS=array(); $strHash=''; $strGzipContent=''; $intLastModified=0; //    foreach ((array)$this->scripts as $file){ if (substr($file,0,5)=='http') continue; if ($file[0]=='/') $strFilename=sys_root.$file; else $strFilename=sys_root.'app/front/view/'.$file; $strHash.=$file; //     $strGzipContent.=file_get_contents($strFilename); $intLastModified=$intLastModified<filemtime($strFilename) ? filemtime($strFilename) : $intLastModified; } $strGzipHash=md5($strHash); $strGzipFile=sys_root.'app/front/view/js/bin/'.$strGzipHash.'.gz'; //    gz- if (file_exists($strGzipFile) && $intLastModified>filemtime($strGzipFile) || !file_exists($strGzipFile)){ if (!file_exists($strGzipFile)) touch($strGzipFile); //    php  zlib   $gz = gzopen($strGzipFile,'w9'); gzputs ($gz, $strGzipContent); gzclose($gz); } //     $arrNewJS[]='js/bin/'.$strGzipHash.'.gz'; $this->scripts=$arrNewJS; } 

I will not write about css, the idea is similar. The only question is in automating caching and in order of incoming files. However, as a result of compression, 5 requests turned into 1, and the total size decreased by 3 times.
Read the same



Original

')

Source: https://habr.com/ru/post/27210/


All Articles