頁面資源多、載入慢的時候,讓使用者盯著半白的畫面乾等是最糟的體驗。加一層遮罩與轉圈動畫,就能明確告知「正在載入」,同時避免誤點擊。
function initialize() {
addcloud(); // 加上遮罩
document.onreadystatechange = subSomething; // 監聽載入狀態
}
function addcloud() {
var bodyWidth = document.documentElement.clientWidth;
var bodyHeight = Math.max(document.documentElement.clientHeight,
document.body.scrollHeight);
// 遮罩層
var bgObj = document.createElement("div");
bgObj.setAttribute('id', 'bgDiv');
bgObj.style.position = "absolute";
bgObj.style.top = "0";
bgObj.style.left = "0";
bgObj.style.background = "#000000";
bgObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75)";
bgObj.style.opacity = "0.5";
bgObj.style.width = bodyWidth + "px";
bgObj.style.height = bodyHeight + "px";
bgObj.style.zIndex = "10000"; // 墊在最上層,攔住所有點擊
document.body.appendChild(bgObj);
// Loading 動畫
var loadingObj = document.createElement("div");
loadingObj.setAttribute('id', 'loadingDiv');
loadingObj.style.position = "absolute";
loadingObj.style.top = bodyHeight / 2 - 32 + "px";
loadingObj.style.left = bodyWidth / 2 + "px";
loadingObj.style.background = "url(../img/loading.gif)";
loadingObj.style.width = "32px";
loadingObj.style.height = "32px";
loadingObj.style.zIndex = "10000";
document.body.appendChild(loadingObj);
}
function removecloud() {
$("#loadingDiv").remove();
$("#bgDiv").remove();
}
function subSomething() {
if (document.readyState == "complete") { // 載入完畢,移除遮罩
removecloud();
}
}
Math.max(clientHeight, scrollHeight) 確保內容超出視窗時遮罩仍能蓋滿整頁。filter 給舊 IE,opacity 給標準瀏覽器。document.onreadystatechange 會依序經歷 loading → interactive → complete,因此這個回呼也能用來在其他階段插入不同邏輯。如果不必支援舊 IE,直接用 CSS 就能取代大半程式碼:
.mask {
position: fixed; inset: 0;
background: rgba(0,0,0,.5);
z-index: 10000;
}
再搭配 window.addEventListener('load', ...) 移除節點即可,程式碼量大幅縮減,也免去了手動計算寬高的麻煩。