Warning: Parameter 1 to wp_default_scripts() expected to be a reference, value given in /home/webgalli/public_html/blog/wp-includes/plugin.php on line 571

Warning: Parameter 1 to wp_default_scripts() expected to be a reference, value given in /home/webgalli/public_html/blog/wp-includes/plugin.php on line 571
improve website speed with lazyloading images and save bandwidths - Team Webgalli Blog
Request quote

Lazy load images and save bandwidths of your website

Posted on: June 30th, 2012 by Sarath C No Comments

This tutorial will help you to load your website faster by implementing lazyloading for all the <img> tags. Most of the time server-side render time is probably not the bottleneck of your page performance… Usually its the, the front-end is the most significant contributor to page load time. Things like <img> tags and css images are one of the most frequent contributors to page load time because these assets are loaded by the browser, even if they’re not visible to the user.

Lazy Load is a jQuery plugin written in JavaScript. It delays loading of images in long web pages. Images outside of viewport (visible part of web page) wont be loaded before user scrolls to them which is opposite of image preloading.

Using Lazy Load on long web pages containing many large images makes the page load faster. Browser will be in ready state after loading visible images. In some cases it can also help to reduce server load.

What if you have all this content and images on your page, you say? What are you to do?

One technique is to use lazy loading of images as users scroll down the page. By implementing lazy loading, you free up resources such as bandwidth, available http connections, and client-cpu to render the content within the browser viewport quickly. Then, worry about additional content as the user scrolls down the page. This will make the initial page load faster and outputs something to browser than keeping the user waiting in front of a white screen.

To implement it use a spacer.gif as the src of images, and include the width and height of the final image.

<img src="spacer.gif" class="lazy" data-src="/images/fullsize.jpg" width="240" height="152"></a>

Add the following code to the <head></head> section of your website

/* lazyload.js (c) Lorenzo Giuliani
 * MIT License (http://www.opensource.org/licenses/mit-license.html)
 *
 * expects a list of:  
 * `<img src="spacer.gif" data-src="fullsize.png" width="240" height="152" class="lazy">`
 */

!function(window){
  var $q = function(q, res){
        if (document.querySelectorAll) {
          res = document.querySelectorAll(q);
        } else {
          var d=document
            , a=d.styleSheets[0] || d.createStyleSheet();
          a.addRule(q,'f:b');
          for(var l=d.all,b=0,c=[],f=l.length;b<f;b++)
            l[b].currentStyle.f && c.push(l[b]);

          a.removeRule(0);
          res = c;
        }
        return res;
      }
    , addEventListener = function(evt, fn){
        window.addEventListener
          ? this.addEventListener(evt, fn, false)
          : (window.attachEvent)
            ? this.attachEvent('on' + evt, fn)
            : this['on' + evt] = fn;
      }
    , _has = function(obj, key) {
        return Object.prototype.hasOwnProperty.call(obj, key);
      }
    ;

  function loadImage (el, fn) {
    var img = new Image()
      , src = el.getAttribute('data-src');
    img.onload = function() {
      if (!! el.parent)
        el.parent.replaceChild(img, el)
      else
        el.src = src;

      fn? fn() : null;
    }
    img.src = src;
  }

  function elementInViewport(el) {
    var rect = el.getBoundingClientRect()

    return (
       rect.top    >= 0
    && rect.left   >= 0
    && rect.top <= (window.innerHeight || document.documentElement.clientHeight)
    )
  }

    var images = new Array()
      , query = $q('img.lazy')
      , processScroll = function(){
          for (var i = 0; i < images.length; i++) {
            if (elementInViewport(images[i])) {
              loadImage(images[i], function () {
                images.splice(i, i);
              });
            }
          };
        }
      ;
    // Array.prototype.slice.call is not callable under our lovely IE8 
    for (var i = 0; i < query.length; i++) {
      images.push(query[i]);
    };

    processScroll();
    addEventListener('scroll',processScroll);

}(this);

For non javascript browsers

its better to add a placeholder for the image.

<img src="spacer.gif" class="lazy" data-src="/images/fullsize.jpg" width="240" height="152"></a>
<noscript><img src="img/fullsize.jpg" width="240" heigh="152"></noscript>

and to hide both from appearing together by adding the following css

.lazy {
  display: none;
}

Lazyloader for WordPress

There is a plugin available for wordpress here.

Thats it. You can see a demo of it at

  • http://webgalli.com/ (the home page slider)
  • http://webgalli.com/blog/ (all the featured images in that post.
Tags: , , , , , ,