Gzip aggregated CSS and JS

Owen Barton - December 4, 2006 - 10:03
Project:Drupal
Version:7.x-dev
Component:base system
Category:feature request
Priority:normal
Assigned:Unassigned
Status:needs work
Issue tags:CSS aggregation, Needs usability review, Performance
Description

This is a follow on from #100516 - CSS preprocessor (and, originally #81835), which is a patch to aggregate multiple CSS files into a single (cached) file.

This patch (which should be applied on top of the #100516 patch):

  • Adds an option to the settings to gzip this cached file.
  • If enabled then it gzips and saves a .css.gz file in addition to the regular .css file and...
  • Adds a .htaccess rule to use this file if the browser accepts gzip and the gz file exists.

As you can see, it is a very simple addition, but should be very valuable for heavy sites. Apart from the time saved for users, there is a 16Kb bandwidth saving too - potentially several GB of bandwidth a year for a site with several 100K visitors.

I currently have this flagged as a feature request for 5.0, but it could very well be considered a usability enhancement.

Here are my original benchmarks:
-----------------------------------------

<?php
          HEAD
          Total       Transfer Duration       Page Duration
Test 1    12798       8756                    8454
Test 2    12984       8907                    8162
Test 3    12730       8718                    7966
Average   12837       8794                    8194
Baseline  100
%        100%                    100%
                    
         
conditional_css_include_2.patch
          Total       Transfer Duration       Page Duration
Test 1    10633       7111                    6828
Test 2    11225       7332                    7530
Test 3    11047       7639                    7357
Average   10968.33    7361                    7238
Faster By 15
%         16%                     12%
                    
         
cache_19.patch
          Total       Transfer Duration       Page Duration
Test 1    9160        5453                    5175
Test 2    9417        5712                    4961
Test 3    9056        5306                    5290
Average   9211        5490                    5142
Faster By 28
%         38%                     37%

         
conditional_css_include_2.patch AND cache_19.patch
          Total       Transfer Duration       Page Duration
Test 1    9595        5615                    5333
Test 2    9909        5709                    5425
Test 3    9461        5824                    5537
Average   9655        5716                    5432
Faster By 25
%         35%                     34%

         
cache_19.patch AND gzip
          Total       Transfer Duration       Page Duration
Test 1    7429        3495                    2741
Test 2    7027        3306                    2758
Test 3    6915        3267                    3001
Average   7124        3356                    2834
Faster By 45
%         62%                     65%

         
conditional_css_include_2.patch AND cache_19.patch AND gzip
          Total       Transfer Duration       Page Duration
Test 1    7489        3157                    2395
Test 2    6699        3107                    2364
Test 3    7250        3013                    2255
Average   7146        3092                    2338
Faster By 44
%         65%                     71%
?>

* Testing was done locally, to eliminate the variable latency you get on live networks. The Charles web debugging proxy was used to apply a consistent throttle and latency equivalent to a typical 64Kbps connection.
* Browser caching was disabled completely, to simulate an initial page load. I can repeat, with caching enabled (to test http cache freshness checks) if that would be useful.
* Drupal page caching (css caching for #100516) was enabled, and the test was done as an anonymous user. All Drupal modules were enabled (a few of these would more likely be contrib modules in reality). The page cache was cleared before each set of tests, and 2 dummy reloads were made before starting timing.
* The first column 'Total' is the total time spent transferring data, as reported by Charles. This does not include the time saved by browser pipelining of http requests.
* The second column 'Transfer Duration' is the Duration between the first byte transfer and the last byte transfer, as reported by Charles
* The third column 'Page Duration' is the time between the end user hitting refresh and Firefox finishing building the page. This is occasionally less that the transfer duration, which is a little odd, but perhaps certain page graphics (favicons maybe?) are not included in the page build time.

Note that these percentages are compared to the times in my original HEAD benchmark (with no patches) at http://drupal.org/node/100516#comment-162025
Please read the notes on that comment if you have not done so already. Also note that all the conditional css includes patch is doing here is somewhat reducing the cached css size, because none of the conditions are met on the front page.

Here is a summary:

<?php
Test Set                     Faster By
Seconds Saved:
HEAD                         100%        0
conditional                  12
%         1
caching                      38
%         3
conditional
+ caching        34%         3
caching
+ gzip               65%         5.3
conditional
+ caching + gzip 71%         5.8
?>

Looking at this I am actually wondering if we should be looking at including gzipped css (and js) in core - if not for 5.0 - then certainly in 6.0. While the percentages are skewed by the fact that my test page is pretty lightweight (i.e. not much content, and no user added images) the seconds saved are real, actual seconds that would be saved by a user on a 64Kbps connection, and would be saved no matter what is added to the site and theme in the way of content and additional images. Also note that the conditional includes patch has now been committed to HEAD, but wasn't when I did my initial benchmarks - I am keeping it separate here for easier comparison.

Bearing in mind the statistic that most users will only wait 4 seconds before going to a different site, the application of aggregation/caching and gzip can take the initial page load time from a very poor 7 or 8 seconds, to a very respectful 2 seconds. The difference between these patches is extremely noticeable, the site goes from feeling pretty sluggish to appearing extremely fast.

AttachmentSizeStatusTest resultOperations
gzip_css_1.patch.txt2.62 KBIgnoredNoneNone

#1

lennart - December 4, 2006 - 12:13

Personally, I think this is critical. Initial page load time is a critical factor for first time visitors. This one almost cuts the initial load time in half. Very significant!

#2

Owen Barton - December 4, 2006 - 15:31

I just noticed a typo in the benchmark tables - 'Faster By' for HEAD should of course be 0% (or N/A!), not 100%.

#3

moshe weitzman - December 4, 2006 - 15:38
Status:needs review» needs work

we have outstanding bugs on our gzipped page cache (if first person to view a page has gzip disabled, we still cache that page and send wrong headers). i'd rather see that resolved before we add more gzip.

the implementation here is a bit more interesting since the logic is in .htaccess. is there no performance penalty for this .htaccess check on every request?

also, don't we have to tell the browser that we are sending gzip in the response headers? are we expecting browser to know because filename ends in .gz?

the #description doesn't explain anything about gzip

#4

m3avrck - May 24, 2007 - 02:53
Version:5.x-dev» 6.x-dev

Subscribing... this should handle CSS and JS files...

#5

Owen Barton - May 24, 2007 - 18:32

There is a different (better, I think) approach in my sandbox: http://cvs.drupal.org/viewcvs/drupal/contributions/sandbox/grugnog/gzip_... - which should deal with css, js and a few other things too.

I think moshe was right about the headers (in terms of following specs), so the .htaccess option is probably out (although it did work cross-browser).

#6

m3avrck - June 1, 2007 - 16:30

With 4 weeks to go, let's see if we can get this in :-)

Owen, did you want to start with a patch based off of your module? If not, I can try and post one in the next few days.

#7

catch - November 7, 2007 - 15:02
Version:6.x-dev» 7.x-dev

#8

Wim Leers - January 27, 2008 - 18:35

Subscribing.

#9

Wim Leers - January 27, 2008 - 18:48
Title:Gzip aggregated CSS to cut 2 seconds off initial load» Gzip aggregated CSS and JS

Since JS aggregation is now in Drupal 6 core as well, I suggest we tackle both CSS and JS aggregation here.

#10

satynos - February 18, 2008 - 05:07

subscribing...

#11

DanielTheViking - April 20, 2008 - 11:46

Subscribing.

#12

BioALIEN - April 21, 2008 - 02:47

This had huge potential but unfortunately didn't make it into 6.x. What's holding up the progress on this patch? Is it because of the outstanding bugs on gzipped page cache in core?

Also I agree with Grugnog2 in #5 about the use of .htaccess method, while it is browser compatible, Dries highlighted his desire to make core compatible with lighttpd and other web servers. We should put some consideration for those too if possible.

#13

oNyx - May 6, 2008 - 06:25

On my site a typical page is around 100kb in size. About 75kb of that are aggregated js (50kb) and css (25kb) files, which can be compressed down to about 25kb (with stripped comments 17kb).

Even without stripping comments it would cut it in half for first time visitors. And you can get a whole torrent of those from social bookmarking sites. My puny little page gets about 3000 of those occasionally and I'm currently on some cheap shared host. So, it generates about 300mb instead of 150mb. That's a pretty big difference if you ask me.

Since the number of visitors is constantly rising I really would love to see that kind of thing in core ASAP. Otherwise I'll need to switch to some more expensive hosting plan a few months sooner than actually necessary.

#14

alanburke - June 29, 2008 - 16:24

subscribing

#15

chirale - June 29, 2008 - 16:46

This topic is pretty hot nowadays, I read two related discussions on contrib modules for 5.x: this one minify the Javascript aggregated file, and this is about "statical" gzipping method. Today I start to use both the approaches combined, and the result is fine. Since aggregation is a core task, I leave this to a small bash script run on cron job. Should JSMin patch to Javascript Aggregator be reused here?

#16

oNyx - July 4, 2008 - 22:29

Got tired of waiting and just added it to my installation. Only requires 14 extra lines in .htaccess and 2 in common.inc. These 2 lines need to be added again after updating, but imo it's totally worth the hassle.

The step by step guide is over here:
How to GZip Drupal 6.x's aggregated CSS and JS files

#17

Susurrus - July 5, 2008 - 03:34

It seems that Zlib support isn't standard for a PHP installation, at least not on non-Windows OSes. Can someone confirm this?

If this is the case, it might stand in the way of adding this.

#18

oNyx - July 5, 2008 - 15:44

Surprisingly you're correct. It's silly, but there are indeed a few installations without Zlib support.

If it's implemented as an option, it would be a good idea to guard the setting (defaults to off) with a function_exists('gzencode') condition.

Fortunately the level parameter for gzencode exists since 4.2 and Drupal requires 4.3.5+. So, at least that part won't be an issue.

#19

Susurrus - July 5, 2008 - 16:48

Well, Drupal 7 requires 5.2+, so that's definitely not an issue. I would think this would need to be implemented like Clean URLs, where the option to enable gzip encoding would be disabled if the function doesn't exist with an explanation of why.

How about a reroll as an option in the Performance settings page?

#20

lilou - August 31, 2008 - 03:57

subscribe.

#21

AltaVida - November 4, 2008 - 04:42

subscribe

#22

Owen Barton - December 26, 2008 - 23:19
Status:needs work» needs review

Here is a patch, based somewhat on the original patch I posted, but with improvements based on http://kaioa.com/node/78 and http://drupal.org/node/290280

Here is how this should work
* It should fail safe to the regular uncompressed aggregated CSS or JS in almost every situation. This includes gzencode not being available (e.g. on very cut down windows PHP builds), if mod_rewrite is not available and enabled, if the gz file is not found or the browser does not accept gzip encoded data.
* It sends both the correct file extension (i.e. we don't ask the browser to request a .gz file, but just rewrite the request behind the scenes) and also the correct MIME type for the file.
* It does not involve any kind of PHP bootstrap at all - everything is done at the Apache level. In addition, the .htaccess files are created dynamically within the files/X directories, meaning that we don't invoke additional rewrite rule tests (a concern of Moshe in #3) or clutter up an already complex /.htaccess.
* There is no additional user interface cruft. We don't have options for core page level gzipping and I don't see any need for them here, as long as we give it sufficient testing cross-platform. This is a no-brainer.

I have tested this on my system and it worked very well, on the first run in fact (the general approach is also quite battle hardened on many production sites).

If you want to test this out you can do this by applying the patch and then checking the response headers using the "Net" tab in Firebug or a similar tool for both .css and .js files. You should see "Content-Encoding gzip" in there and also notice a noticeable drop in file size.

If someone would like to write some tests to polish this off that would be a valuable contribution.

AttachmentSizeStatusTest resultOperations
gzip.patch3.12 KBIdlePassed: 13643 passes, 0 fails, 0 exceptionsView details | Re-test

#23

Rob Loach - December 27, 2008 - 02:15
Status:needs review» needs work

Is there any reason why we're checking function_exists with gzencode? Drupal 7 requires at least PHP 5.2, so wouldn't it be safe to assume it's available?

As for tests, I'd love those to go in with this patch, but won't have the chance to hit it up until next week because I'll be off on vacation. Otherwise, great work! Also, does that clear cache functionality remove the respective .htaccess file?

#24

Owen Barton - December 27, 2008 - 14:38

@Rob Loach

We are testing function_exists with gzencode for the same reason we do this with the core page gzipping code. Zlib support for PHP is extremely common, but is actually not enabled in a default vanilla compile of PHP (even in 5.2), so it is quite possible that it will not be available - "Zlib support in PHP is not enabled by default. You will need to configure PHP --with-zlib[=DIR]" from http://www.php.net/manual/en/zlib.installation.php

If you have a chance to do some tests that would be awesome!

The cache clearing functions do not remove the .htaccess file - all dot files are excluded. This shouldn't matter either way, since the file would be recreated anyway and is harmless if no .gz files are present. Possibly we might want to add a line to delete the .htaccess file at the point when aggregation is disabled (although it causes no issue if it is there), or perhaps even the js/css directory in it's entirety (on the basis that it is cruft and could be confusing to a newbie).

#25

catch - December 27, 2008 - 22:45

We do have a UI for core page gzipping - see 'page compression' at admin/settings/performance - and it's a useful thing to have if you're using mod_deflate/mod_gzip etc. We could reword the interface text there and use the same variable for both things though - seems like it'd be the same reason for switching one off as switching off the other.

#26

janusman - January 6, 2009 - 15:09

subscribing

#27

kenorb - January 14, 2009 - 02:12

I'm not quite understand, why Drupal don't gziping all other pages, even browser have support for gip (I'm not talking about js and css).
I've tried to found it, but without result. Somebody know some link to the topic?

#28

Rob Loach - January 14, 2009 - 02:45

I think this should be solely be managed through contrib once #352951: Make JS Preprocessing Pluggable is in.

#29

btully - February 5, 2009 - 16:20

subscribe

#30

mikeytown2 - March 31, 2009 - 20:43

Update: Contributed modules can now do this for 6.x. Once the code freeze is in place (early September), porting these to 7.x shouldn't be that hard.
http://drupal.org/project/javascript_aggregator
http://drupal.org/project/css_gzip

#31

andypost - May 17, 2009 - 02:04

Both modules exclude safari (webkit) so first projects from #30 should be fixed

Safari (webkit) bug https://bugs.webkit.org/show_bug.cgi?id=9521

So there 2 solutions:

1) make filename.css with filename.css.gz.css

2) alternative way is store filename.css (gzipped) and plain filename.nogzip.css

Both work with safari 3 and google chrome

<IfModule mod_rewrite.c>
    RewriteEngine On
# Konqueror and "old" browsers
    RewriteCond %{HTTP:Accept-encoding} !gzip [OR]
    RewriteCond %{HTTP_USER_AGENT} Konqueror
    RewriteRule ^(.*)\.(css|js)$ $1.nogzip.$2 [QSA,L]
</IfModule>    

<IfModule mod_headers.c>
    Header append Vary User-Agent
# for all  css/js files setup Content-Encoding
    <FilesMatch .*\.(js|css)$>
Header set Content-Encoding: gzip
Header set Cache-control: private
    </FilesMatch>
# reset Content-Encoding if not archive
    <FilesMatch .*\.nogzip\.(js|css)$>
Header unset Content-Encoding
    </FilesMatch>
</IfModule>

#32

lilou - May 17, 2009 - 02:38

Add tag.

#33

mikeytown2 - May 17, 2009 - 19:19

#34

andypost - May 17, 2009 - 20:10

#35

mikeytown2 - May 25, 2009 - 22:01
Issue tags:-needs backport to D6

Been thinking about the safari/webkit bug... because of the rewrite rules, the browser only sees it as *.css where on the file system it is *.css.gz. Changing the extension around would have no effect; in short it's not a bug because the html file doesn't reference *.css.gz it still points to *.css (bug report deals with *.css.gz in the html code). With that in mind this is a fairly straight forward patch for D7, the question is will it be accepted if I write one?

There are 3 functional changes that need to take place
http://api.drupal.org/api/function/drupal_build_css_cache/7 - write *.css.gz files
http://api.drupal.org/api/function/drupal_build_js_cache/7 - write *.js.gz files
http://api.drupal.org/api/function/system_performance_settings/7 - add gzip compression settings

Add this to .htaccess, inside <IfModule mod_rewrite.c> right above # Rewrite URLs of the form 'x' to the form 'index.php?q=x'.

  <FilesMatch "\.(css.gz)$">
    AddEncoding x-gzip .gz
    ForceType text/css
  </FilesMatch>
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}.gz -f
  RewriteRule ^(.*)\.css $1.css.gz [L,QSA]
 
  <FilesMatch "\.(js.gz)$">
    AddEncoding x-gzip .gz
    ForceType text/javascript
  </FilesMatch>
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}.gz -f
  RewriteRule ^(.*)\.js $1.js.gz [L,QSA]

#36

chx - May 25, 2009 - 22:01

khm.

AddOutputFilterByType DEFLATE text/css application/x-javascript text/html text/plain text/xml

#37

mikeytown2 - May 25, 2009 - 22:31

@chx, that compresses on the fly for every request; slightly slower. Don't forget about level 9; default is 6 if I remember correctly.

AddOutputFilterByType DEFLATE text/css application/x-javascript text/html text/plain text/xml
DeflateCompressionLevel 9

Core caches gzip html, so it's not a way out there request; plus having settings in the UI is a nice usability feature. It's something most people want IMHO. Great point BTW.

#38

hass - June 3, 2009 - 21:17

#35 doesn't work in IIS.

#39

mikeytown2 - June 3, 2009 - 21:26

how does IIS support conditional gzip, so only the clients that support gzip get gzipped content?

#40

andypost - June 3, 2009 - 21:57

@hass IIS rewrite rules are possible different

#41

hass - June 3, 2009 - 22:29

This is not possible in IIS (for e.g. with Helicon ISAPI_Rewrite, and not at all without payed plugins) and therefore no general solution:

<FilesMatch "\.(css.gz)$">
    AddEncoding x-gzip .gz
    ForceType text/css
</FilesMatch>

#42

hass - June 3, 2009 - 22:27

@mikeytown2: IIS does not have any GZIP compression feature build in for dynamic files (only for static HTML files). You need to buy extra plugins to archive this - if you think you really need it...

#43

mikeytown2 - June 11, 2009 - 08:15

Shrunk gzip .htaccess rules. Escaped all periods . for possible performance increase with pattern matching since . means any character. Anyone wants to test the escaped period hypothesis out?

Option 1

  <FilesMatch "\.gz$">
    AddEncoding x-gzip \.gz
  </FilesMatch>
  #skip gzipped css/js files if browser doesn't accept gzip encoding
  RewriteCond %{HTTP:Accept-encoding} !gzip
  RewriteRule .* - [S=2]
  #CSS
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule (.*)\.css$ $1\.css\.gz [L,QSA,T=text/css]
  #JS
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule (.*)\.js$ $1\.js\.gz [L,QSA,T=text/javascript]

Option 2

  <FilesMatch "\.gz$">
    AddEncoding x-gzip \.gz
  </FilesMatch>
  #CSS
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule (.*)\.css$ $1\.css\.gz [L,QSA,T=text/css]
  #JS
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule (.*)\.js$ $1\.js\.gz [L,QSA,T=text/javascript]

Option 3 (no escaped periods)

  <FilesMatch "\.gz$">
    AddEncoding x-gzip .gz
  </FilesMatch>
  #skip gzipped css/js files if browser doesn't accept gzip encoding
  RewriteCond %{HTTP:Accept-encoding} !gzip
  RewriteRule .* - [S=2]
  #CSS
  RewriteCond %{REQUEST_FILENAME}.gz -s
  RewriteRule (.*)\.css$ $1.css.gz [L,QSA,T=text/css]
  #JS
  RewriteCond %{REQUEST_FILENAME}.gz -s
  RewriteRule (.*)\.js$ $1.js.gz [L,QSA,T=text/javascript]

Which way would be preferred: 1, 2 or 3?

#44

mikeytown2 - June 21, 2009 - 03:27
Status:needs work» needs review

Gzip setting controlled by page_compression. Trying to make this as simple as possible.

AttachmentSizeStatusTest resultOperations
gzip-101227.patch2.69 KBIdleFailed: Failed to install HEAD.View details | Re-test

#45

hass - June 21, 2009 - 11:13

What will happen if the server do not support GZ compression or any of this Apache rewrite rules?

#46

Owen Barton - June 21, 2009 - 14:50

The attached patch includes the same conditional checks as page gzipping, so should fail where php has no zlib. The .htaccess will only trigger for .gz files exist, so nothing should break there.

The only thing I was wondering is if the rewrite rules for this should also be within a block (which could also contain the mime rule) - because if rewrite is enabled but mime isn't it seems there is a possibility of the type being incorrect, right?

AttachmentSizeStatusTest resultOperations
gzip-101227-2.patch3.99 KBIdleFailed: Failed to install HEAD.View details | Re-test

#47

hass - June 21, 2009 - 15:48

This fails on IIS:

+<FilesMatch "\.js\.gz$">
+  ForceType text/javascript
+</FilesMatch>

But this will work:

+  # Serve gzip compressed js files
+  RewriteCond %{HTTP:Accept-encoding} gzip
+  RewriteCond %{REQUEST_FILENAME}\.gz -s
+  RewriteRule (.*)\.js$ $1\.js\.gz [L,QSA,T=text/javascript]

In such a case the ForceType may not send to the browser, but the compressed file is... I'm not sure if this could cause issues!?

#48

mikeytown2 - June 21, 2009 - 17:59

Due to apache weirdness I'm setting the type twice. Once globally in the FilesMatch argument; the other time with T=text/javascript in the RewriteRule. That seems to work 100% of the time on various versions of apache. Does IIS work with T= ?

#49

hass - June 21, 2009 - 20:22

#50

mikeytown2 - June 21, 2009 - 23:59

hass, good to hear that works. Here's a slight adjustment to #46, adjusted the regular expression for the rewrite rule so it compares from the start, instead of from the end. Should always work with *.css?5 and things like that. The reason I need both T=MIME-type and the FilesMatch argument is because the newest version of apache doesn't work with T=MIME-type; well you can get it to work if you do some ugly tricks, so FilesMatch is the best way to get around the apache inconsistencies.
http://httpd.apache.org/docs/trunk/mod/mod_rewrite.html#rewriterule

'type|T=MIME-type' (force MIME type)
Force the MIME-type of the target file to be MIME-type. This can be used to set up the content-type based on some conditions. If used in per-directory context, use only - (dash) as the substitution, otherwise the MIME-type set with this flag is lost due to an internal re-processing.

http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriterule

'type|T=MIME-type' (force MIME type)
Force the MIME-type of the target file to be MIME-type. This can be used to set up the content-type based on some conditions. For example, the following snippet allows .php files to be displayed by mod_php if they are called with the .phps extension:

AttachmentSizeStatusTest resultOperations
gzip-101227-3.patch4.13 KBIdleFailed: Failed to apply patch.View details | Re-test

#51

System Message - June 24, 2009 - 01:10
Status:needs review» needs work

The last submitted patch failed testing.

#52

mikeytown2 - June 24, 2009 - 07:38
Status:needs work» needs review

Another reason why this should be in core
http://code.google.com/speed/articles/gzip.html

Above patch should still be good... re-submitting it.

#53

System Message - June 27, 2009 - 20:10
Status:needs review» needs work

The last submitted patch failed testing.

#54

andypost - July 1, 2009 - 11:50
Status:needs work» needs review

Suppose bot was broken, so re-test

#55

meba - July 6, 2009 - 19:31

Works for me. What happens if the user doesn't change .htaccess as this file is usually kept? I understand that nothing will happen for him and he won't see a difference.

Can the new rewrite rules negatively affect performance?

#56

mikeytown2 - July 6, 2009 - 20:04
Status:needs review» reviewed & tested by the community

@meba
if the .htaccess file is not changed, then nothing happens; gzipped files do not get served. Performance impact is minimal; I haven't done any benchmarking though; It's hard for me to get access to an idle computer (my benchmarking results would be very unreliable for this small of a change).

#57

meba - July 6, 2009 - 20:32
Status:reviewed & tested by the community» needs review

Would it be possible to decide whether to serve gzipped file directly in Drupal? We should have accept-encoding header available when printing styles.

#58

mikeytown2 - July 6, 2009 - 20:43

I don't understand your question, but here's an answer that hopefully answers what you where trying to say.

The new rules look to see if a css.gz file exists; if it does, that gets sent to the browser. If aggregation is turned off, and you compressed the css files your self, it will serve those as well (css.gz files in themes, ect...). If aggregation is on, printing styles get aggregated; thus they get gzip compressed.

#59

meba - July 6, 2009 - 21:01

I know how does it work. What I mean is that we already check for gzip encoding capability in bootstrap.inc.

Why don't we just use that information (make return_compressed drupal static?) or simply check again in drupal_get_css and link to gzipped files without a need for additional rewrite rules?

bootstrap.inc:

  $return_compressed = $page_compression && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE;

drupal_get_css():

    if ($is_writable && $preprocess_css) {
      // Prefix filename to prevent blocking by firewalls which reject files
      // starting with "ad*".
      $filename = 'css_' . md5(serialize($types) . $query_string) . '.css';
// COULD RETURN GZIPPED FILEPATH IF SUPPORTED?
      $preprocess_file = drupal_build_css_cache($types, $filename);
      $output .= '<link type="text/css" rel="stylesheet" media="' . $media . '" href="' . file_create_url($preprocess_file) . '" />' . "\n";
    }

#60

mikeytown2 - July 6, 2009 - 21:08

Your proposal would make the page cache more complicated. it would require 2 different html sets; one with style.css, another with style.css.gz. It would also be incompatible with older webkit browsers (Apple Safari).

#61

andypost - July 7, 2009 - 03:28
Status:needs review» reviewed & tested by the community

@meba anyway we need send specific header for css so this produceв by rewrite rules

Agree with #60, aggregation could be changed but all cached pages,css,js always cleared by system_clear_cache_submit at admin/settings/performance

But UI changes fro different issue

#62

hass - July 9, 2009 - 11:12

Have one of you verified this in IIS with Helicons ISAPI Rewrite? We are trying to do the same in our non Drupal app and it's not working.

May be related to missing IIS support of:

AddEncoding x-gzip .gz

#63

mikeytown2 - July 11, 2009 - 23:15

@hass
Can you send out custom content encoding types in IIS? I don't use IIS so you're sorta on your own.

#64

hass - July 12, 2009 - 01:16

We tried to do the same in our ColdFusion application on IIS6, but we haven't found a solution yet. I haven't found the time to test the above patch, but I expect after our tests this will result in a broken Drupal site (the gzip'ed CSS/JS files are send to the browser without encoding gzip).

The ISAPI_Rewrite solution from Helicon-Tech do not have the ability to send responds headers. Helicon "Ape" seems to have such a feature, but is only implemented well on IIS7, plus I do not have "Ape". Not sure if there are other ISAPI add-ons for IIS available with such a functionality...

#65

andypost - July 13, 2009 - 16:54

So maybe better to return to different naming css.gz replace with gz.css

#66

hass - July 13, 2009 - 17:30

How should this help?

#67

andypost - July 16, 2009 - 20:37

I have no env to test rewrite with IIS

#68

sun - July 19, 2009 - 04:44
Status:reviewed & tested by the community» needs work

This needs to be togglable separate from page compression. People might want to use different methods for compression of page requisites/support files (such as mod_deflate).

#69

andypost - July 23, 2009 - 17:41

UI rework is here #459980: Rework admin/settings/performance

But this issue mostly about css-js compression

#70

mikeytown2 - August 8, 2009 - 03:12
Status:needs work» needs review

@hass
Have you looked at The Microsoft URL Rewrite Module for IIS 7.0

@sun
Good point. I was kind of hoping that #459980: Rework admin/settings/performance would be in by now... anyway here is the patch with more fine-grained control.

AttachmentSizeStatusTest resultOperations
gzip-101227-70.patch4.81 KBIdleFailed: Failed to apply patch.View details | Re-test

#71

mikeytown2 - August 8, 2009 - 03:39

here's one that defaults to FALSE just in case that is the desired way to do this.

AttachmentSizeStatusTest resultOperations
gzip-101227-71.patch4.83 KBIdleFailed: Failed to apply patch.View details | Re-test

#72

sun - August 8, 2009 - 03:53

+++ .htaccess 8 Aug 2009 03:21:52 -0000
@@ -7,6 +7,16 @@
+# Gzip compressed css files are of the type 'text/css'.
...
+# Gzip compressed js files are of the type 'text/javascript'.

"CSS" and "JS" should be written all-upper-case here.

+++ .htaccess 8 Aug 2009 03:21:52 -0000
@@ -89,6 +105,16 @@ DirectoryIndex index.php index.html inde
+  RewriteRule ^(.*)\.css $1\.css\.gz [L,QSA,T=text/css]
...
+  RewriteRule ^(.*)\.js $1\.js\.gz [L,QSA,T=text/javascript]

I see a conversion from .* to .*.gz, but where are those (page) requests handled?

+++ includes/common.inc 8 Aug 2009 03:21:54 -0000
@@ -2627,6 +2627,10 @@ function drupal_build_css_cache($css, $f
+    if (variable_get('css_gzip_compression', TRUE) && function_exists('gzencode') && zlib_get_coding_type() == FALSE) {
@@ -3324,6 +3328,10 @@ function drupal_build_js_cache($files, $
+    if (variable_get('js_gzip_compression', TRUE) && function_exists('gzencode') && zlib_get_coding_type() == FALSE) {

Oh my - with this patch applied, we have this (complex) check at several places throughout core.

At the very least, we want to add a comment what is being checked here and more importantly, why.

Ideally, though, we want to create a helper function that performs those conditions centrally and just returns the result.

+++ modules/system/system.admin.inc 8 Aug 2009 03:21:55 -0000
@@ -1373,6 +1373,13 @@ function system_performance_settings() {
+  $form['bandwidth_optimizations']['css_gzip_compression'] = array(
...
+    '#disabled' => !variable_get('preprocess_css', 0),
@@ -1381,6 +1388,13 @@ function system_performance_settings() {
+  $form['bandwidth_optimizations']['js_gzip_compression'] = array(
...
+    '#disabled' => !variable_get('preprocess_js', 0),

This means I can't enable bandwith optimizations while enabling preprocessing optimizations? That's ugly UX.

23 days to code freeze. Better review yourself.

#73

mikeytown2 - August 8, 2009 - 04:32

I've addressed your first 2 concerns.


Ideally, though, we want to create a helper function that performs those conditions centrally and just returns the result.

This could be useful... this is what core does in drupal_page_set_cache()

<?php
   
if (variable_get('page_compression', TRUE) && function_exists('gzencode')) {
     
// We do not store the data in case the zlib mode is deflate. This should
      // be rarely happening.
     
if (zlib_get_coding_type() == 'deflate') {
       
$cache_page = FALSE;
      }
      elseif (
zlib_get_coding_type() == FALSE) {
       
$cache->data = gzencode($cache->data, 9, FORCE_GZIP);
      }
     
// The remaining case is 'gzip' which means the data is already
      // compressed and nothing left to do but to store it.
   
}
?>

Whats your recommendation on this?


This means I can't enable bandwidth optimizations while enabling preprocessing optimizations? That's ugly UX.

How should it be done? Gzip does nothing unless it has aggregated files to play with. Gzip only works if Optimize is enabled, and that is how it's setup.
'#disabled' not '#enabled' ;)

AttachmentSizeStatusTest resultOperations
gzip-101227-73.patch5.01 KBIdleFailed: Failed to apply patch.View details | Re-test

#74

sun - August 8, 2009 - 04:49

As far as I get it: #disabled _really_ only is when: (function_exists('gzencode') && zlib_get_coding_type() == FALSE) === TRUE

As far as the form is concerned, I'd just go with above condition for #disabled. And let the UX team figure out how to handle dependent configuration settings like this - in a separate issue. (please)

However, I still don't get how *.css.gz or *.js.gz files are handled on the server-side, based on the rewrite rules applied here. Perhaps, I'm just dumb, but it seems like *.css is rewritten to *.css.gz, and Apache will expect those files already exist, while I'm too blind to see a condition that checks whether they really exist?

+++ .htaccess 8 Aug 2009 04:25:43 -0000
@@ -89,6 +105,16 @@ DirectoryIndex index.php index.html inde
+  RewriteCond %{REQUEST_FILENAME}\.gz -s
...
+  RewriteCond %{REQUEST_FILENAME}\.gz -s

Or is it the -s option?

All we could do about those aforementioned compression conditions is to create a new drupal_server_compression_enabled() function. Not sure whether that makes ultimately sense, and most probably, this should be deferred to a separate issue... :-/

#75

mikeytown2 - August 8, 2009 - 05:03

Good point with #disabled. That should probably be added to the page_compression checkbox as well.

<?php
  $form
['page_cache']['page_compression'] = array(
   
'#type' => 'radios',
   
'#title' => t('Page compression'),
   
'#default_value' => variable_get('page_compression', TRUE),
   
'#options' => array(t('Disabled'), t('Enabled')),
   
'#description' => t("By default, Drupal compresses the pages it caches in order to save bandwidth and improve download times. This option should be disabled when using a webserver that performs compression."),
  );
?>

Apache: It's the -s option. that checks that the file exists and filesize > 0, which all valid gzipped files should be, even if empty.

Also word wrapped the long comment inside the drupal_build_*_cache() functions.

AttachmentSizeStatusTest resultOperations
gzip-101227-75.patch5.1 KBIdleFailed: Failed to apply patch.View details | Re-test

#76

kika - August 8, 2009 - 08:28

For binary choices I would go for simpler checkbox:

[ ] Enable page compression

#77

System Message - August 13, 2009 - 06:50
Status:needs review» needs work

The last submitted patch failed testing.

#78

mikeytown2 - August 13, 2009 - 18:36
Status:needs work» needs review

#459980: Rework admin/settings/performance went in, so I raised up some issues with it.

Here's the patch again. After encountering a misconfigured server on the boost forum, I did some research and almost no one sends out x-gzip anymore, so i switched it to gzip going against the apache documentation (ie 5.5 sends out gzip, so I think it's stuff like Netscape 3 that uses x-gzip).

AttachmentSizeStatusTest resultOperations
gzip-101227-78.patch5.13 KBIdleFailed: Failed to install HEAD.View details | Re-test

#79

mikeytown2 - August 19, 2009 - 23:49

Found a use case where having this in core would be nice. #554146: CSS_GZip doesn't work with Pixture and other color-based themes.

#80

System Message - August 20, 2009 - 12:22
Status:needs review» needs work

The last submitted patch failed testing.

#81

mikeytown2 - August 20, 2009 - 17:10
Assigned to:Anonymous» mikeytown2
Status:needs work» needs review

re-rolled

AttachmentSizeStatusTest resultOperations
gzip-101227-81.patch5.13 KBIdlePassed: 13663 passes, 0 fails, 0 exceptionsView details | Re-test

#82

doq - August 22, 2009 - 19:38
Status:needs review» needs work

aggergated -> aggregated

#83

doq - August 22, 2009 - 19:42

1. What about renaming variable "css_gzip_compression" to "css_compression" (the same for js).
2. And "Gzip compress JavaScript aggergated files" to "Compress JavaScript aggregated files" (the same for css)?

3. Looks incorrect (see the comment):

<?php
+    $form['bandwidth_optimization']['js_gzip_compression'] = array(
+     
'#type' => 'checkbox',
+     
'#title' => t('Gzip compress JavaScript aggergated files'),
+     
'#default_value' => variable_get('css_gzip_compression', FALSE), //// Should be js_gzip_compression
?>

#84

Owen Barton - August 22, 2009 - 21:22
Status:needs work» needs review

Updated patch to move the various rules into a single block, and ensure that they are all dependent on BOTH mod_rewrite and mod_mime being enabled (the previous patch broke if you had mod_rewrite enabled, mod_mime disabled, which while unusual is not impossible). I tried to improve the comments as well, to make some of the nuances mentioned in this thread clearer - I think it is certainly easier to see what is going on when the rules are in a single block. We could probably be even more detailed here if we wanted, but I don't want to make it unnecessarily verbose.

I left the settings in for now, but I think these are mostly unnecessary (I can't reproduce any problems even if I have AddOutputFilterByType DEFLATE in my .htaccess) and if we can add a check to see if the webserver (or a proxy) is already gzipping files, as suggested in #459980: Rework admin/settings/performance I think all these settings could be removed.

AttachmentSizeStatusTest resultOperations
gzip-101227-84.patch5.02 KBIdlePassed: 13632 passes, 0 fails, 0 exceptionsView details | Re-test

#85

sinasalek - August 26, 2009 - 19:23

subscribing

#86

mikeytown2 - August 26, 2009 - 19:35
Assigned to:mikeytown2» Anonymous

+1 for Owen Barton's patch

#87

Owen Barton - August 26, 2009 - 22:25

Looking up the reasoning behind the checkbox for page compression (http://drupal.org/node/121820 and a few others linked from that one) it seems pretty clear that all the problems that led to it's insertion were related to interaction with PHP's zlib.output_compression setting causing double compression of pages. In other words our js and css gzipping should not be affected by this issue, since they do not use the output buffer. Hence here is a patch with the GUI removed (I left the variable_get in there so someone could disable in settings.php $conf array if they really like). If a committer has a strong opinion that this needs a GUI then feel free to commit the previous patch, but my preference is "less is more" in this case.

AttachmentSizeStatusTest resultOperations
gzip-101227-86.patch3.15 KBIdleFailed: 13669 passes, 1 fail, 0 exceptionsView details | Re-test

#88

doq - August 26, 2009 - 22:30
Status:needs review» needs work

#89

doq - August 26, 2009 - 22:30
Status:needs work» needs review

#90

andypost - September 23, 2009 - 16:36
Status:needs review» needs work

+1 to #87 - I see no need in setting, only if someone get a trouble with double compression can uncomment line in settings.php

So better to make a line with comment in default.settings.php

#91

andypost - October 2, 2009 - 02:05
Status:needs work» needs review
Issue tags:+Needs usability review

If compression issue will be commited #43462: cache_set and cache_get base_url brokenosity
So we can omit this setting at all.

#92

mattyoung - October 2, 2009 - 06:06

.

#93

System Message - October 5, 2009 - 03:20
Status:needs review» needs work

The last submitted patch failed testing.

#94

casey - November 20, 2009 - 14:55
Issue tags:+CSS aggregation

tagging (there are many topics about css aggregation)

 
 

Drupal is a registered trademark of Dries Buytaert.