js懒加载思想和单张图片的懒加载
2017-04-18 本文已影响33人
SmallTwo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box{
margin-top: 800px;
width: 300px;
height: 200px;
background: red;
}
#img{
width: 90%;
height: 90%;
}
</style>
</head>
<body>
<div id="box">
<img src="" alt="" id='img' data-origion="http://cdnimg2.edu.euming.com/pkuie/20151128/s_1448682060094_T0iGqY.jpg@480w">
</div>
<script>
var box = document.getElementById('box'),imgs = document.getElementById('img');
var imgH = parseFloat(getComputedStyle(imgs,null).height) + imgs.offsetTop;
window.onscroll = function () {
var scrolH = (document.documentElement.clientHeight || document.body.clientHeight) + (document.documentElement.scrollTop || document.body.scrollTop);
if (imgs.loaded) return;
if (imgH < scrolH) {
console.log('haha');
var newImage = new Image;
newImage.src = imgs.getAttribute('data-origion');
newImage.onload = function () {
imgs.src = this.src;
newImage = null;
imgs.loaded = true;
}
}
}
</script>
</body>
</html>