Skip to content

Latest commit

 

History

History
56 lines (47 loc) · 1.73 KB

图片懒加载的实现.md

File metadata and controls

56 lines (47 loc) · 1.73 KB
title date tag
图片懒加载的实现
2016-09-25 16:24:00 -0700
Lazyload

原理

  1. 图片懒加载就是先不加载,src里面写一个占位图,然后自定义一个data属性,比如data-src。
  2. 然后绑定滚动事件
  3. 待到页面滚动到图片的上方时,就把图片的data-src值写入src里,这样加载就完成了。

实现

这是HTML,loading是一个占位图

<img src="loading.jpg" data-src="lazy.png">

这里是两种实现方式

// js实现,抱歉,兼容性不高,但是很有学习意义。如果是在webview里面,这种方法也可行
window.addEventListener('scroll', function(){
	Array.prototype.slice.call(document.querySelectorAll('img')).forEach(function(v) {
            var fold = window.innerHeight + (document.documentElement.scrollTop || document.body.scrollTop);
            if (fold >= v.offsetTop && !v.classList.contains('lazy')) {
                var src = v.getAttribute('data-src');
                v.setAttribute('src', src);
                v.classList.add('lazy');
            }
        });
});
// 首屏加载触发
var event = document.createEvent("HTMLEvents");
event.initEvent("scroll", true, true);
window.dispatchEvent(event);



// jQuery实现,兼容各种浏览器
$(window).on('scroll', function() {
      	$('img').each(function() {
      		var fold = $(window).height() + $(window).scrollTop();
      		if (fold >= $(this).offset().top && !$(this).hasClass('lazy')) {
      			var src = $(this).attr('data-src');
      			$(this).attr('src', src);
      			$(this).addClass('lazy');
      		}
      	});
});
// 首屏加载触发
$(window).trigger('scroll');

如果嫌麻烦,可以直接使用jQuery的lazyload插件,专门实现懒加载