We have discussed Data URI schemes previously and how they help reducing number of HTTP requests for CSS images.
Today I have developed a patch to Drupal 6.x core that will inject images into CSS file when Optimize CSS files option is turned on. This patch embeds only images less then 1K in size. Follow the comments for more information:
Index: includes/common.inc =================================================================== --- includes/common.inc (revision 0) +++ includes/common.inc (working copy) @@ -1931,10 +1931,35 @@ $last = $path; $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path); } + + $path2 = substr($path, strlen(base_path())); + // Embed images that are less then 1K in size. + if ($image = image_get_info($path2)) { + if ($image['file_size'] < 1024) { + $path = data_uri_scheme($path2, $image['mime_type']); + } + } + return 'url('. $path .')'; } /** + * Generate data URI scheme to be used inside url() attribute. + * + * @param $file + * File path to generate data URI scheme from. + * @param $mime + * MIME type of file, e.g. image/png, image/gif. + * @return + * Data URI scheme to be used inside url() attribute. + */ +function data_uri_scheme($file, $mime) { + $contents = file_get_contents($file); + $base64 = base64_encode($contents); + return 'data:'. $mime .';base64,'. $base64; +} + +/** * Loads the stylesheet and resolves all @import commands. * * Loads a stylesheet and replaces @import commands with the contents of the
Results
Data URI schemes were tested on the web-site that has 12 background images on the homepage (all of them where 1K less in size so all became embedded into CSS). I have received the following results:
| Without patch | With patch applied | |
|---|---|---|
| Optimized CSS file size | 57.2K |
82.7K |
| Optimized CSS file size (GZIPed) | 11.2K |
24.3K |
| Number of CSS images | 12 |
0 |
| CSS images size | 2.5K |
0 |
13K more data to transfer (comparing GZIPed CSS file) but this might be faster even then 2.5K of images and 12 HTTP requests to them. This should speed up your Drupal web-site for new visitors significantly.
[Update 2009 Dec 12]
This patch won't work for browsers that do not support data URI schemes. These are IE6 and IE7. The newer solution will try to take care of workaround for these browsers and you still can see surfing speed up in Firefox, Safari, IE8 and other popular browsers: Speed up Drupal web-site by reducing HTTP requests using data URI schemes: second attempt.
| Attachment | Size |
|---|---|
| Drupal 6.x embed CSS images using data URI schemes.patch | 1.16 KB |

Comments
Post new comment