Optimising the CSS & JavaScripts using PHP in 3 steps

4th January, 2010

Imagine yourself moving 11 times, each time moving a package and each time having to confirm the package is received. It’s the same process with a browser – having 5 CSS files and 6 JavaScript files in a website is a normal thing these days. But put yourself in your server’s position! Sending 11 files and confirming each time if the browser received the file…
It is possible, but wouldn’t it be better if you could send all your CSS files at once and all your JavaScript files at once by using php? By using the include function, it’s easy to include all your CSS files to a file called “master_css.php” and all your JavaScript files in to a folder called “master_js.php”, then call them all together throughout your pages.
Another thing you can do is to remove the things that browsers ignore i.e., removing “whitespace”. This includes comments and new lines. It can be difficult to remove them all by yourself, plus it does make the code unreadable. So to remove what is never going to be used, change all your line comments (//) into paragraph comments (/* */) and add to a function file the following function:

function compress($buffer) {
/* remove comments */
$buffer = preg_replace(‘!/\*[^*]*\*+([^/][^*]*\*+)*/!’, ”, $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array(“\r\n”, “\r”, “\n”, “\t”, ‘ ‘, ‘ ‘, ‘ ‘), ”, $buffer);
return $buffer;
}

Once you have done that, remove everything useless from your “master_css.php” & “master_js.php” by adding the following code:

< ?php

header(‘Content-type: text/css’);
include(‘myfunctions.php’); //add your function
ob_start(“compress”); //call the function /* your css or JavaScript files, please don’t include them together */ include($_SERVER[‘DOCUMENT_ROOT’].’/interactive10 /style.css’);
include($_SERVER[‘DOCUMENT_ROOT’].’/style.css’);
ob_end_flush();

Now if everything up to this point is done correctly, you should have one CSS and one JavaScript file, each being about 50% smaller than they were previously. You can halve that number by adding two additional lines at the end of your code:

ob_start(“ob_gzhandler”); just before ob_start(“compress”); and ob_end_flush();
By doing these things, you will make your code cleaner and decrease the load on your server, making your website faster!