Tag Archives: background-image

Do background-images lazy-load with display:none?

So, do background-images lazy-load with display:none? I did a quick test by loading this testpage created by Steve Souders on webpagetest.org. These are the results:

Conclusion: don’t rely on setting display:none on background-images to have them lazy load.

Dipping below the magical 1 second page load time

A couple of weeks ago I started looking into data-uri’s as a way to further optimize the performance of this personal playground of mine. Testing was easy enough; Autoptimize, the javascript/ css/ html opitimizing plugin I now use in conjunction with WP Super Cache, comes with support for data-uri’s in CSS and switching that option on indeed immediately resulted in less requests being made.

While testing I did find a small bug in Autoptimize (in /wp-content/autoptimize/classes/autoptimizeStyles.php) which caused jpeg images not to be taken into account. The regular expression in the code was ‘jpe?j’, while just below in a switch/case block ‘jpej’ and ‘jpg’ were referenced, resulting in neither ‘.jpg’ nor .’jpeg’ files ever being turned into data-uri’s. While reading the code I also noticed that the upper filesize limit for images to be turned into data-uri’s was set at 5120 bytes, but as base64-encoding does come with overhead, I decided to lower that limit to 2560 bytes.

So I made some minor changes in autoptimizeStyles.php on lines 207 and following:

if($path != false && preg_match('#\.(jpe?g|png|gif|bmp)$#',$path) && file_exists($path) && is_readable($path) && filesize($path) <= 2560) {
   switch(end(explode('.',$path))) {
      case 'jpeg':
         $dataurihead = 'data:image/jpeg;base64,';
         break;
      case 'jpg':
         $dataurihead = 'data:image/jpeg;base64,';
         break;
      case 'gif':
...

I also  switched my “subscribe” widget from a paragraph- to a bulleted list-approach with the rss- and mail-icons as background images and defined the adfreeblog and creative commons badges as background-images as well. And then I was ready to test the real impact of using data-uri’s on webpagetest.org. Behold the results for my current blog homepage (i.e. the one just before this post got published) with and without the use of data-uri’s (but excluding those dog-slow calls to stats.wordpress.com):

No data-uri’sWith data-uri’s
webpagetest results URLhttp://www.webpagetest.org/result/121106_12_6FZ/http://www.webpagetest.org/result/121106_4H_71R/
#requests (full page)2619
Bytes in (full page)116KB114KB
Start render (median)0.615s0.634s
Doc Complete time (median)0.969s0.870s
Full page load time (median)1.932s1.332s

Let it be clear that the use of data-uri’s for background-images is not a silver bullet, but if you have images that are on every page of your site and they’re small in file-size, migrating those into your CSS as background-images with data-uri’s can result in an important performance improvement for your site.