图片懒加载插件

﹏ヽ暗。殇╰゛Y 2022-06-06 08:07 1158阅读 0赞






  1. </body>
  2. <script src="echo.js"></script>
  3. <script>

window.onload = function(){
Echo.init({
offset: 200, //设置图片距离可视区域多少像素被加载(纵向)
throttle: 1050 //设置图片延迟加载的时间
});
}

  1. </script>

echo.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-echo’);
store.splice(i, 1);
}
}
};

var _throttle = function() {
clearTimeout(poll);
poll = setTimeout(_pollImages, throttle);
};

var init = function(obj) {
var nodes = document.querySelectorAll(‘[data-echo]‘);
var opts = obj || {};
offset = opts.offset || 0;
throttle = opts.throttle || 250;

for (var i = 0; i < nodes.length; i++) {
store.push(nodes[i]);
}

_throttle();

if (document.addEventListener) {
window.addEventListener(‘scroll’, _throttle, false);
} else {
window.attachEvent(‘onscroll’, _throttle);
}
};

return {
init: init,
render: _throttle
};

})(window, document);

发表评论

表情:
评论列表 (有 0 条评论,1158人围观)

还没有评论,来说两句吧...

相关阅读

    相关 图片

    在一个项目中,如果同时加载的图片太多的话,会导致页面卡顿,这个时候就会用到懒加载。懒加载的实现原理是监听浏览器的滚动条事件,先加载出前面几张图片,然后当滚动条滚动的时候再依次加

    相关 图片

    懒加载的意义[(在线demo预览)][demo] 尽管很多公司的网页都有一些限制,比如页面的最大的图片大小不得大于50k,也有很多图片优化工具fis3、gulp等等,但是