*{padding: 0;margin: 0}
img{width: 100%;display: block;}
// 图片加载js代码
window.Echo=(function(window,document,undefined){'use strict';var store=[],offset,throttle,poll;var _inView=function(el){var coords=el.getBoundingClientRect();return((coords.top>=0&&coords.left>=0&&coords.top)<=(window.innerHeight||document.documentElement.clientHeight)+parseInt(offset));};var _pollImages=function(){for(var i=store.length;i--;){var self=store[i];if(_inView(self)){self.src=self.getAttribute('data-src');store.splice(i,1);}}};var _throttle=function(){clearTimeout(poll);poll=setTimeout(_pollImages,throttle);};var init=function(obj){var nodes=document.querySelectorAll('[data-src]');var opts=obj||{};offset=opts.offset||0;throttle=opts.throttle||250;for(var i=0;i
Echo.init({
offset: 100,//离可视区域多少像素的图片可以被加载
throttle: 0,//图片延时多少毫秒加载
els: '.jsLoadImg',
elP: '.lazy-img',
dataSrc: 'data-src'
});
原理是把真实的图片路径放在src里面,先加载src里面的小图片,等页面滚动到相应的位置,就把src的内容赋给src。
主要代码是“图片预加载js代码”,然后调用传参数,跟使用jquery插件一样,只不过这里不需要jquery。
效果如下:
1、没有预加载的时候要加载13M
2、有预加载的时候只需先加载2.6M
因为我这里用的图片很多都是在不同的域名下的,所以它们可以同时加载,如果图片都是在同一域名下的效果更佳明显。