Thursday, March 19, 2009

How to reduce the size of JavaScript & CSS file?

Compress JavaScript / CSS file with the help of gzip:-

With the help of php ob_start() function we can create gzip file for JavaScript.

if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], ‘gzip’))
ob_start(”ob_gzhandler”);
else
ob_start();
?>

We can use above code at the beginning of the JavaScript and code at the end. So output of Php file is JavaScript code in gzip encrypted form.

In this method, we have to save JavaScript files as a .php file.

By compressing the plan text JavaScript file with the help of gzip; its size gets reduced by more than 60%. Smaller the file size, better the download time.

Reduce the size of JavaScript and CSS file by removing the white spaces, carriage return and comments:-

We can also remove the white spaces, carriage return and comments from JavaScript files to reduce its size. Every single letter or space in your HTML code takes up one byte. It doesn’t sound like much but it all adds up. By working through page source and eliminating unnecessary white space and comments, we can shave off up to, or even over 10% of its file size.

No comments: