保证页面打开速度(如果3S内首页打不开,已经算是死亡页面了)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片延迟加载/懒加载</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
font-family: 微软雅黑;
font-size: 14px;
}
.banner {
margin: 10px auto;
width: 790px;
height: 340px;
border: 1px solid green;
background: url(default.jpg) no-repeat center center #e1e1e1;
}
.banner img {
display: none;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="banner">
<img id="jd" trueImg="jd2.jpg" src="" alt="">
</div>
<script>
window.onload = function () {
var banner = document.getElementById('banner');
var jd = document.getElementById('jd');
jd.src = jd.getAttribute('trueImg');
jd.onload = function () {
jd.trueImg = '';
jd.style.display = 'block';
}
jd.onerror = function(){
console.log('error');
}
}
</script>
</body>
</html>
window.onload = function () {
/*var oImg = document.createElement('img');*/
var jd = document.getElementById('jd');
var src = jd.getAttribute('trueImg');
var oImg = new Image();
oImg.src = src;
//图片能够正常加载
oImg.onload = function(){
jd.src = src;
jd.style.display = 'block';
oImg = null;
var nowTime = new Date();
console.log('图片加载完成,耗时'+(nowTime - time)+' ms');
}
console.log('图片加载中......');
var time = new Date();
}