首页 > 代码库 > 图片延迟加载源码分析!

图片延迟加载源码分析!

 1 <!DOCTYPE html> 2 <html lang="en"> 3  4 <head> 5     <meta charset="UTF-8"> 6     <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7     <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8     <title>图片延迟加载</title> 9     <style type="text/css">10         #box {11             width: 790px;12             height: 340px;13             border: 1px solid red;14             margin: 20px auto;15             background: url("./img/jddongtu.gif")no-repeat center center;16         }17         #lazyImg {18             display: none;19         }20     </style>21 </head>22 23 <body>24     <div id="box">25         <img  trueImg="./img/jd02.jpg" id="lazyImg">26     </div>27     <script type="text/javascript">28         var lazyImg = document.getElementById(‘lazyImg‘);29         var timer = window.setTimeout(function () {30             // body31             var oImg = new Image;32             oImg.src = http://www.mamicode.com/lazyImg.getAttribute("trueImg");33             oImg.onload = function () {34                 // 图片能正常加载时,就进行图片展示;35                 lazyImg.src = http://www.mamicode.com/this.src;36                 lazyImg.style.display = "block";37                 oImg = null;38             }39         }, 1000)40     </script>41 </body>42 43 </html>

 

图片延迟加载源码分析!