懒加载

it2022-05-09  25

"use strict";

var imgLazy = { checkWebp : function() { try { return ( document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp')==0 ); } catch(err) { return false; } }, checkImgUrl : function(imgurl, imgObj) { imgObj.src = imgurl; imgObj.onerror = function() { imgObj.src = imgurl.replace(/.webp$/, '.jpg'); imgObj.onerror = null; }; }, getImgTop : function(img) { var offsetTop = img.getBoundingClientRect().top, winHeight = document.documentElement.clientHeight || document.body.clientHeight; if (offsetTop < winHeight+2000) { return true; } }, lazyLoadImg : function(imgsrc) { var img = document.getElementsByTagName("img"); for (var i = 0, length = img.length; i < length; i++) { if (img[i].getAttribute(imgsrc)) { img[i].style.opacity = .5; img[i].style.filter = "alpha(opacity = " + 50 + ")"; if ( this.getImgTop(img[i]) ) { var url = img[i].getAttribute(imgsrc).replace(/.jpg$/, '.webp'); // 判断浏览器是否支持.webp格式 if( this.checkWebp() ) { // 判断有没有.webp图片 this.checkImgUrl(url, img[i]); } else { img[i].src = img[i].getAttribute(imgsrc); } img[i].removeAttribute(imgsrc); img[i].style.webkitTransition = 'opacity 1s'; img[i].style.opacity = 1; img[i].style.filter = "alpha(opacity = " + 100 + ")"; } } } }, throttle : function(method, parma,context) { clearTimeout(method.tId); method.tId = setTimeout(function(){ method.call(context, parma); }, 200); }, init : function() { var oThis = this; oThis.lazyLoadImg('data-src'); window.onscroll = function() { oThis.throttle(oThis.lazyLoadImg, 'data-src', oThis); }; }};imgLazy.init();

转载于:https://www.cnblogs.com/znj211985211/p/7232946.html

相关资源:JQuery LazyLoad 图片懒加载实例

最新回复(0)