`

Lazy Load Image & WordPress Gravatar using JavaScript / JQuery

阅读更多

文章源自:http://viralpatel.net/blogs/lazy-load-image-wordpress-avatar-jquery/

Lazy Load Image & WordPress Gravatar using JavaScript / JQuery

Lazy Image Loading

After doing all these changes still if you have lots of images on your website, you might want to lazy load these images. Meaning load the image only when it is being viewed there by deferring http call until user is watching the image.

This technique can be very much useful in websites which display list of products with images. User can scroll through list and instead of loading all the product images while loading webpage, each image is loaded asynchronously when it comes in users viewport.

Now to achieve this we use simple JQuery snippet:

Step 1: Change <IMG> tag

First change the <img> tag for which you want to lazy load image to:

<!-- Before: -->
<img src="http://foo/product.png" width="300px" height="200px" />

<!-- After: -->
<img src="blank.gif" class="lazy" data-src="http://foo/product.png" 
			width="300px" height="200px" />

 

Notice how we moved our image url from src to data-src attribute. Also we added blank.gif which is 1 px transparent gif file in src attribute. We also added a CSS class lazy to the image. This is to mark the image for lazy loading in jquery code which we will see shortly. Also do not forget to mention height and width attribute with <img> tag. This make sure browser leave enough space around blank.gif to load original image.

Now on pageload, browser will load blank.gif file instead of product.png thus making http request more faster. If you have several images with src=blank.gif, browser will load it just once and use it from cache.

Step 2: The JQuery Code Snippet

We want to load original image once that image is in browsers visible area. Following JQuery snippet do this task.

(function($) {
	var lazyloadImage = function(){

		$('img.lazy').each(function(){
			var distanceToTop = $(this).offset().top;
			var scroll = $(window).scrollTop();
			var windowHeight = $(window).height();
			var isVisible = distanceToTop - scroll < windowHeight;
			if (isVisible) {
				$(this).attr('src', $(this).attr('data-src')).removeClass('lazy');
			}
		});

	};

	$(function(){
		$(window).scroll(function() {
			lazyloadImage();
		});
	});

	lazyloadImage();

})(jQuery);

 In this snippet we hook a function to browsers scroll event. For each image that has lazy css class on it, we iterate and see if the image is in visible area. If it is then we just copy value from image’s data-src to its src attribute. Once the image’s src attribute changes, browser will automatically load its content. Note how we remove lazy class once the image is loaded to avoid further changes in DOM.

Further Optimization using data URI

The above image lazy loading technique reduce the page size significantly during the load time, but it still performs an http request on blank.gif. If somehow browser is not caching blank.gif image, then it will unnecessarily perform multiple http requests for it for each lazy image.

We can further optimize this by using Data URIs. It is a technique by which image data is directly embedded into document using some URI instead of linking external images within element or background-image in CSS.

The biggest reason why you want to do this is to save HTTP Requests.

Just change the <img> tag we saw previously to:

<!-- Before: -->
<img src="blank.gif" class="lazy" data-src="http://foo/product.png" 
			width="300px" height="200px" />

<!-- After: -->
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" 
		class="lazy" data-src="http://foo/product.png" 
			width="300px" height="200px" />

 

So intead of linking to external image blank.gif, we embedded its content in src attribute of <img> element using data URI. This will significantly reduces number of http requests in your webpage.

SEO Consideration

Lazy loading images would improve site speed significantly. But it also makes images less crawlable. Search engines like Google indexes the images from a website and display those in Image search. So if your website’s main source of traffic is image search than you may not want to implement this optimization technique.

But as I said earlier, there is always room for optimization. You can keep main images on your webpage as it is and make other less significant images to load dynamically. For example the Avatar images that you display in each comment. These images are not significant for indexing. A blog article can be showing 50 comments each with an Avatar image. Instead of loading 50 images during pageload, you can make them lazy by using our lazy code snippet.

I Don’t Want To Use JQuery

If you are not keen on using JQuery snippet as you might not using JQuery alltogether in your website! No worries. Following JavaScript code from Lorenzo Giuliani does exactly same thing.

/* lazyload.js (c) Lorenzo Giuliani
 * MIT License (http://www.opensource.org/licenses/mit-license.html)
 *
 * expects a list of:  
 * `<img src="blank.gif" data-src="my_image.png" width="600" height="400" 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);

 

ust add above JavaScript code in your site and you are good to go.

 

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    jquery.lazyload图片预加载效果 jquery预加载

    《jQuery LazyLoad 图片预加载技术详解》 在网页设计中,图片的加载速度往往直接影响着用户体验。当页面中包含大量图片时,如果一次性全部加载,可能会导致页面加载时间过长,用户需要等待,这无疑降低了网站的可用...

    JQuery Lazyload加载图片实例

    **jQuery Lazyload 图片加载技术详解** 在网页设计中,图片是重要的元素之一,但大量图片的预加载可能会拖慢页面的加载速度,影响用户体验。为了解决这一问题,jQuery 提供了一个插件——jQuery Lazyload,它允许...

    JQuery LazyLoad 图片懒加载实例

    jQuery LazyLoad 是一个轻量级的JavaScript插件,它允许我们只加载当前可视区域内的图片,其余图片则在用户滚动页面时逐步加载。这种方法显著减少了首次页面加载的时间,提高了用户体验,同时也节省了带宽资源。 ##...

    jquery.lazyload.js

    jQuery.Lazyload.js是一个高效实用的JavaScript插件,它能够显著提升网页加载速度,同时赋予网页图片渐显效果,从而创造出既美观又高效的网页浏览体验。 jQuery.Lazyload.js的核心原理在于"懒加载"(Lazy Loading)...

    jquery.lazyload 实现图片延迟加载

    使用 `jQuery LazyLoad` 非常简单,首先需要在页面中引入 jQuery 和 LazyLoad 的 JavaScript 文件,然后按照以下步骤配置: 1. **标记图片**:给需要延迟加载的图片添加特定的类名,例如 `lazyload`。 2. **初始化...

    jQuery_lazyload

    jQuery_lazyload是一个非常实用的JavaScript库,用于优化网页性能,特别是在处理大量图片或者内容时。这个插件的主要目的是延迟加载,即在用户滚动到页面的特定部分时才加载那些可视区域以外的内容,从而减少初次...

    jquery.lazyload.js 图片懒加载 --demo

    **jQuery LazyLoad.js 图片懒加载技术详解及Demo演示** 在网页设计中,图片加载是一项重要的性能优化策略。尤其对于内容丰富的网站,一次性加载所有图片可能会导致页面加载速度变慢,影响用户体验。为了解决这个...

    jquery lazyload延时加载

    1. **引入 jQuery 和 LazyLoad**:首先确保页面中已经引入了 jQuery 库,然后引入 LazyLoad 的 JavaScript 文件,如 `jquery.lazyload.js`。 2. **设置 HTML 结构**:给需要延时加载的图片添加特定的类名(如 `lazy...

    jQuery.lazyload.js

    Lazy Load 是一个用 JavaScript 编写的 jQuery 插件. 它可以延迟加载长页面中的图片. 在浏览器可视区域外的图片不会被载入, 直到用户将页面滚动到它们所在的位置. 这与图片预加载的处理方式正好是相反的. 在包含很多...

    lazyload-2.x.zip

    《jQuery LazyLoad 2.x API详解与应用实践》 在当今网页开发中,为了提高页面加载速度和用户体验,"懒加载"(Lazy Load)技术变得越来越重要。jQuery LazyLoad插件是一个广泛使用的解决方案,它允许图片、iframe等...

    jquery.lazyload.min.js

    jquery.lazyload.min.js插件 直接下载引入即可~~~~~~~

    lazyload-JavaScript

    **标题:“lazyload-JavaScript”** 在网页开发中,图片懒加载(Lazy Load)是一种优化用户体验和提高页面加载速度的技术。"lazyload"是指在JavaScript中实现的延迟加载策略,它只在用户滚动到视口附近的图片时才...

    前端项目-jquery-lazyload-any.zip

    《前端项目中的jQuery LazyLoad Any技术详解》 在前端开发中,优化网页加载速度和用户体验是至关重要的。jQuery LazyLoad Any是一个高效的插件,专为延迟加载图像、iframe或者其他任何元素而设计,它大大提升了页面...

    懒加载lazyload

    `jquery.lazyload.js` 是基于 jQuery 的懒加载插件,而 `jquery-1.11.0.min.js` 是 jQuery 的一个小巧且经过压缩的版本,用于支持 `jquery.lazyload.js` 的运行。`tuupola-jquery_lazyload` 这个压缩包可能包含了这...

    jQuery.lazyload-1.7.2

    jQuery.lazyload 是一个非常流行的JavaScript插件,专用于优化网页性能,通过实现图片的懒加载技术。这个插件的核心理念是延迟非视口内的图片加载,直到用户滚动页面并接近这些图片时才进行加载。这样可以显著减少...

    jquery lazyload图片延迟加载技术

    **jQuery LazyLoad 图片延迟加载技术** 在网页设计中,图片是重要的元素之一,但大量图片的加载往往会导致页面加载速度变慢,用户体验下降。为了解决这个问题,开发者们引入了图片延迟加载(Lazy Load)技术。...

    jquery.lazyload

    首先确保在页面中引入了jQuery库和`jQuery.lazyload`插件的JavaScript文件: ```html &lt;script src="https://code.jquery.com/jquery-3.x.y.min.js"&gt;&lt;/script&gt; &lt;script src="jquery.lazyload.min.js"&gt;&lt;/script&gt; ``` ...

    Lazy Load Plugin for jQuery demo

    1. `jquery.lazyload.js`:这是插件的主要 JavaScript 文件,包含实现懒加载功能的代码。 2. `demo.html`:一个演示页面,展示了如何在实际项目中应用插件,并可能包含了不同配置和用法的示例。 3. `images/`:可能...

    前端开源库-jquery-lazyload

    jQuery LazyLoad 是一个非常流行的JavaScript库,专用于实现图片和其他元素的延迟加载。这个开源库允许我们在网页滚动时只加载可视区域内的图片,从而减少了页面初始化时的负担,提升了页面加载速度。 **1. jQuery ...

Global site tag (gtag.js) - Google Analytics