How to compress JS and CSS pages to a server with no gzip and deflate
We will do our best to compress the pages.
The required conditions:
- hoster didn’t enable gzip and deflate compression
- you should have access to .htaccess file
- php should support gzencode (PHP 4+) function
- Clear URLs should be enabled
Compress pages
Open index.php file (it is located in the root of your site) and find the following line here:
print theme(‘page’, $return);
Insert the following command just before this line:
“ob_start(“ob_gzhandler”);”
Why we don’t do this in page.tpl.php?
We want to output the service pages compressed, and choose the theme for the site. And it takes too long to add this line to all themes…
Now browser gets all site pages compressed.
Aggregate CSS and JS
Open “Performance” page (admin/settings/performance) and enable “Aggregate and compress CSS files“. Thus all CSS files will be aggregated to the one file. As far as we know that the hosting doesn’t allow compressing, let we have one CSS file which is not compressed yet.
Enable aggregation of JS scripts in Drupal 6. As the result, browser get the following when requesting the page:
- HTML-page (compressed)
- One css-file (not compressed)
- One JS-file (not compressed)
- Graphoc files
No we should compress these CSS and JS files…
Compress CSS and JS
We will need SmartCache module. Download it and adjust.
- Create “smartcache” folder in /modules/
- Download “load.php” file from the downloaded archive to /modules/smartcache/
- Create a new folder (‘cache’) in /modules/smartcache/ i.e. /modules/smartcache/cache
- Set cache right for the folder to 775
Check how the compression works
Open the following page in your browser: http://example.com/modules/smartcache/load.php?file=misc/drupal.js
If you see usual js, everything works fine. If no, please read readme.txt from the module complectation.
Let’s continue. Open .htaccess file from the root of the site and find the last line with “RewriteRule” and insert the code after it:
RewriteRule ^(.*\.((js)|(css)))$ /modules/smartcache/load.php?file=$1
RewriteRule \.css$ /modules/smartcache/load.php?file=$1
RewriteRule \.js$ /modules/smartcache/load.php?file=$1
In addition, if there is the following rule from “files” folder in .htaccess file:
RewriteEngine on
then delete it. This rule doesn’t allow the required rules work correctly and get the compressed files.
Results
- All pages are compressed by php at every call
- All CSS and JS are also compressed by php. But! The compressed items are stored in cache folder and if there is the required file in the folder – it takes the compressed version.
- The required headers and files are set which decrease server loading.
Now we have a new fun – clear this folder if site theme was changed!