預加載:是提早加載,會增長服務器性能。javascript
懶加載:一、延時加載,二、特定條件加載,三、可視窗口加載(滾動過程當中加載)。css
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box{
width: 200px;height: 200px;
border: 1px solid red;
background: url(img/01.png) center center;
}
</style>
</head>
<body>
<div class="box"></div>
<img src="img/01.png" data-src="http://www.veeqi.com/uploadfile/2016/0924/20160924050538590.jpg"/>
</body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
// 新建圖片數組
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
}
}
// 要加載的網絡圖片資源,以數組形式
preload(
"http://www.veeqi.com/uploadfile/2016/0924/20160924050538590.jpg",
"http://image.uuu9.com/www/news/UploadFiles_7354/201709/201709030034517181.jpg",
"http://img0.utuku.china.com/640x0/game/20170920/13f41313-72b9-4c9c-b7b7-3406751dbe6b.jpg"
);
$(function(){
$(".box").css("background-image","url("+images[0].src+")")
});
// 懶加載
var num = document.getElementsByTagName('img').length;
var img = document.getElementsByTagName("img");
var n = 0; //存儲圖片加載到的位置,避免每次都從第一張圖片開始遍歷
lazyload(); //頁面載入完畢加載但是區域內的圖片
window.onscroll = lazyload;
function lazyload() { //監聽頁面滾動事件
var seeHeight = document.documentElement.clientHeight; //可見區域高度
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滾動條距離頂部高度
for (var i = n; i < num; i++) {
if (img[i].offsetTop < seeHeight + scrollTop) {
// if (img[i].getAttribute("src") == "") {
img[i].src = img[i].getAttribute("data-src");
// }
n = i + 1;
}
}
}html
</script>
java