Compressing your HTML, CSS and Javascript using simple PHP Code

Although Compression is a very important method of making your pages lighter and easier for users to download, it’s definitely going to cost you more CPU and on high load servers it’s not recommended unless you already know how to cache your HTML pages.

GZIP compression
This is highly recommended as it doesn't need any code and generates Gzipped HTML which almost all today browsers can understand. You need to change/add these values on your php.ini

  1. zlib.output_compression = On
  2. zlib.output_compression_level = 9

you can check the size difference online through http://www.gidnetwork.com/tools/gzip-test.php
read more about Gzip

Javascript and CSS compression
I would firstly recommend taking a look on Dean Edwards ’s Packer; a JavaScript compressor which could cut your scripts into half size, you might need to download the PHP class that we would be using on the code to compress the JS scripts.

All .js and .css files should be in one folder “js" and all files should be writable by your server including the folder (chmod -R 777 js).
Now you'll have 2 copies of every JS/CSS file one is readable which you can edit and the other is the compressed file that is included into your HTML using "<script type="text/javascript" language="javascript" src="/js/script.js"></script>" for JS or "<link href="/js/style.css" rel="stylesheet" type="text/css" media="screen" />" for CSS, let’s say our uncompressed files with all the comments and formating is having prefix “local_" before file name then we will always edit that one and dynamically generate the compressed scripts whenever it’s modified.
Here are the functions you need to include

  1.  
  2.  
  3. function JS_check(){
  4.  
  5. $jsfiles = array(’script.js',’style.css'); #add names of scripts you like to generate
  6.  
  7. foreach($jsfiles as $js){
  8.  
  9.  
  10. #if the file doesn't exist or the time stamp time of both compressed and uncompressed files are not near
  11.  
  12. if(!file_exists($_SERVER['DOCUMENT_ROOT']."/js/{$js}") || ($diff = filemtime($_SERVER['DOCUMENT_ROOT']."/js/local_{$js}") - filemtime($_SERVER['DOCUMENT_ROOT']."/js/{$js}")) > 3){
  13.  
  14. if(strpos($js,'.css')===false){ #if a JS file
  15.  
  16. require_once($_SERVER['DOCUMENT_ROOT']."/include/class.JavaScriptPacker.php"); #include Packer class
  17.  
  18. $script = file_get_contents($_SERVER['DOCUMENT_ROOT']."/js/local_{$js}"); #getting JS file
  19.  
  20. $script = str_replace(';;;', '//',$script); #the ;;; comment feature in the packer beta
  21. $packer = new JavaScriptPacker($script, 62, 1, 0); #using Dean Edwards ’s Packer, check documentations on the class file for the best compression level
  22.  
  23. $packed = $packer->pack(); #JS code compressed
  24.  
  25. }else  #if CSS file
  26.  
  27. $packed = css_cmpress(file_get_contents($_SERVER['DOCUMENT_ROOT']."/js/local_{$js}"));
  28.  
  29. file_put_contents($_SERVER['DOCUMENT_ROOT']."/js/{$js}", $packed); #inserting compressed code into files
  30.  
  31. touch($_SERVER['DOCUMENT_ROOT']."/js/local_{$js}"); #change the time stamp time for original scripts
  32.  
  33. #$GLOBALS['debuger'][] = "$js generated, diff was $diff"; #Global array to let you see results
  34.  
  35. }
  36.  
  37. }
  38.  
  39. }
  40.  
  41. function css_cmpress($css){
  42.  
  43. $css = preg_replace('!//[^\n\r]+!', , $css);#comments
  44.  
  45. $css = preg_replace('/[\r\n\t\s]+/s', ' ', $css);#new lines, multiple spaces/tabs/newlines
  46.  
  47. $css = preg_replace('#/\*.*?\*/#', , $css);#comments
  48.  
  49. $css = preg_replace('/[\s]*([\{\},;:])[\s]*/', '\1', $css);#spaces before and after marks
  50.  
  51. $css = preg_replace('/^\s+/', , $css);#spaces on the begining
  52.  
  53. return $css;
  54.  
  55. }
  56.  
  57.  

HTML compression
although this is not very important and the user might get diffrent results than what you expect but I tried to generate HTML without extra spaces, tabs ,newlines or comments that’s not for IE

  1. function html_compress($html){
  2.  
  3. preg_match_all('!(<(?:code|pre).*>[^<]+</(?:code|pre)>)!',$html,$pre);#exclude pre or code tags
  4.  
  5. $html = preg_replace('!<(?:code|pre).*>[^<]+</(?:code|pre)>!', '#pre#', $html);#removing all pre or code tags
  6.  
  7. $html = preg_replace('#<!–[^\[].+–>#', , $html);#removing HTML comments
  8.  
  9. $html = preg_replace('/[\r\n\t]+/', ' ', $html);#remove new lines, spaces, tabs
  10.  
  11. $html = preg_replace('/>[\s]+</', '><', $html);#remove new lines, spaces, tabs
  12.  
  13. $html = preg_replace('/[\s]+/', ' ', $html);#remove new lines, spaces, tabs
  14.  
  15. if(!empty($pre[0]))
  16.  
  17. foreach($pre[0] as $tag)
  18.  
  19. $html = preg_replace('!#pre#!', $tag, $html,1);#putting back pre|code tags
  20.  
  21. return $html;
  22.  
  23. }

The only point is that you could enjoy working using formated tags while giving the user exactly what he needs without any extras, remember that you will always have to save all page output into a single variable then echo it which is usually recommended on small pages while could cost you more memory on large pages.

Updated css function, multi-line /**/ comments are now removed


Tags :

This entry was posted on Saturday, June 23rd, 2007 at 11:22 pm and is filed under Blog. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

4 Responses to “Compressing your HTML, CSS and Javascript using simple PHP Code”

  1. Blogulate Says:

    Great post dude .. worked

  2. Walid GadElKarim » Blog Archive » Dynamic Content Caching using Lighty + mod_magnet + lua Says:

    [...] focus on caching your PHP scripts using Lua and mod_magnet under Lighttpd, You should read “Compressing your HTML, CSS and Javascript using simple PHP Code” as I will use some functions from [...]

  3. shawn Says:

    any idea’s on how i can get my front portal page to load faster (graphics and animation from frontpage)

  4. wkarim Says:

    @Shawn
    there are a lot of ways to speed up static contents of your website, check your server’s configuration optimization tutorials for more info. Most common way is to put them on a separate server with a different sub domain like static.gadelkareem.com and use something like lighttpd to serve static contents.

 

Leave a Reply


 Top