图片懒加载

2021-04-17  本文已影响0人  下班再说

echo.min.js

一款非常简单实用轻量级的图片延时加载插件echo.js,如果你的项目中没有依赖jquery,那么这将是个不错的选择,50行代码,压缩后才1k。当然你完全可以集成到自己项目中去!

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);

demo

<style>

  .demo img {

            width: 736px;

            height: 490px;

            background: url(images/loading.gif) 50% no-repeat;

        }

</style>

<div class="demo">

    <img class="lazy" src="images/blank.gif" data-echo="images/big-1.jpg">

</div>

<script src="js/echo.min.js"></script>

<script>

Echo.init({

    offset: 0,//离可视区域多少像素的图片可以被加载   

    throttle: 0 //图片延时多少毫秒加载});

 </script>

<style>

  .demo img {     width: 736px;     height: 490px;     background: url(images/loading.gif) 50% no-repeat;}

</style>

上一篇下一篇

猜你喜欢

热点阅读