首页 > 其他 > 详细

图片懒加载和预加载

时间:2020-09-05 23:36:14      阅读:70      评论:0      收藏:0      [点我收藏+]
//懒加载
window.onload = function(){ var imgs = Array.from(document.querySelectorAll(‘img‘)); delay(); window.addEventListener(‘scroll‘, exec(delay, 4000)); function exec(fun, delaytime){ var timeout,startTime = new Date(); return function(){ clearTimeout(timeout); tiemout = setTimeout(fun, delaytime); } } function delay(){ var scrollTop = window.scrollY; var clientHeight = document.documentElement.clientHeight; //console.log(clientHeight); imgs.forEach((item, index)=>{ if(scrollTop==0 && item.offsetTop<=clientHeight+scrollTop){ //console.log(item.getAttribute(‘data_img‘)); item.setAttribute(‘src‘,item.getAttribute(‘data_img‘)); }else if(item.offsetTop<=clientHeight+scrollTop && item.offsetTop > scrollTop){ item.setAttribute(‘src‘,item.getAttribute(‘data_img‘)); } }); } }

//预加载
var target = document.getElementById(‘test‘);
addImg(‘./2.jpg‘);
function addImg(url){
    var img = document.createElement(‘img‘);
    var image = new Image();
    image.src=url;
    image.onload = function(){
        img.src = this.src;
                img.height = 50;
                img.width = 50;
    }
    target.appendChild(img);
}
//html
<div id="test"></div>
 

图片懒加载和预加载

原文:https://www.cnblogs.com/connie313/p/13619893.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!