<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style type="text/css">
.image-item {
width: 40%;
margin-right: 5px;
display: inline-block;
height: 350px;
width: 250px;
background: silver;
}
.beauty-list {
margin: 0 auto;
width: 560px;
height: 1200px;
}
.preload{
margin:0 auto 50px auto;
width:560px;
height: 820px;
}
.disN{
display: none;
}
</style>
</head>
<body>
<!--預加載-->
<div class="preload" id="preload">
<!--方式一:通過標籤預先加載圖片資源-->
<img src="https://webimg.quanjing.com/Recommend/1558458888705.jpg" class="image-item disN" />
<img src="https://webimg.quanjing.com/Recommend/1558458860095.jpg" class="image-item disN" />
<img src="https://webimg.quanjing.com/Recommend/1558458906986.jpg" class="image-item disN" />
<img src="https://webimg.quanjing.com/Recommend/1558458916877.jpg" class="image-item disN" />
<!--方式二:通過ajax異步請求資源,缺點:存在跨域問題-->
<script>
//ajax四個步驟
function createXHR(){
var xhr;
try{
xhr = new XMLHttpRequest();
}catch(e){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
try{
xhr = new ActiveObject("Msxml2.XMLHTTP");
}catch(e){
alert("瀏覽器太老,不能使用ajax");
}
}
}
return xhr;
}
// 1. 創建XMLHttpRequest對象
var xhr = createXHR();
xhr.responseType = "blob";
// 2. 調用open方法獲取跟服務器的連接{{ 第一個參數,請求方式:GET|POST,第二個參數,請求路徑:URL,第三個參數,是否異步請求(async):true|false }}
xhr.open('GET','http://127.0.0.1:5500/0.jpg',true);
// 3. 調用send方法, 向服務器發起請求
// 如果是post請求, 那麼需要在send方法中帶請求參數
// 如果是get請求, 那麼參數爲null
xhr.send(null);
// 4. 註冊一個監聽器
/*
不斷地去監聽請求的過程返回的一個狀態碼
在這個時候我們只需要關注readyState == 4的情況,這個時候說明服務器完成了響應
我們還需要關注另外一個狀態碼 status是服務器響應過來的, 需要status == 200
*/
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status == 200) {
//此時說明響應完畢 我們可以通過xml.responseText 來獲取服務器的響應內容(文本內容)
// $("").html(xhr.responseText);
var blob = this.response;
var img = document.createElement("img");
img.onload = function(e) {
window.URL.revokeObjectURL(img.src);
};
img.classList.add('image-item');
img.src = window.URL.createObjectURL(blob);
var pre = document.getElementById('preload');
pre.appendChild(img);
}
};
</script>
<!--方式三:通過preload.js預加載(其實只是綜合前兩種)-->
<script src="https://cdn.bootcss.com/PreloadJS/1.0.1/preloadjs.min.js"></script>
<script>
var queue = new createjs.LoadQueue();
queue.on("complete", handleComplete, this);
queue.loadManifest([
{id: "myImage", src:"http://127.0.0.1:5500/11.jpg"}
]);
function handleComplete() {
var image = queue.getResult("myImage");
image.classList.add('image-item');
var pre = document.getElementById('preload');
pre.appendChild(image);
}
</script>
</div>
</body>
</html>
效果