实现页面懒加载效果的第一步,当然是要先有一个预加载的页面,所以我们先写一个预加载的页面与样式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>
*{
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
#loadingContainer {
position: fixed;
width: 100%;
height: 100%;
background: black;
z-index: 1;
top: 0px;
left: 0px;
color: #ffffff;
}
#loadingContainer div {
text-align: center; //文字居中
width: 300px;
height: 100px;
margin: auto; //水平居中
position: absolute; // 以下代码是为了让div在整个页面垂直居中
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}
.none {
display: none; //可使让元素在页面上隐藏消失
}
</style>
</head>
<body>
<div id="loadingContainer">
<div>
<p>系统初始化中请稍后...</p>
</div>
</div>
</body>
</html>
- 先写一个div,宽高设置为百分百(在此之前浏览器的样式都设置为宽高百分百,内外边距为0,背景颜色为黑色。
- 通过poisiton属性。把值设置为fixed(div相对与整个页面进行定位),把top跟left的值设置为0,使整个页面刷新时候占满整个页面,不设置的话,刷新的时候上左两边会有一部分留白。
(为啥会这样我也不懂,反正这样可以解决这个问题,敲就完事了) - 设置z-index的值为1,让加载的页面优先显示在浏览器上。
下面重点的js出场
(function init(){
document.onreadystatechange = ()=>{
if(document.readyState == "complete")
document.querySelector('#loadingContainer').className = "none";
}
})()
- 编写一个自调的函数,里面调用 document.onreadystatechange。当页面加载状态改变的时候会触发该事件。document里有个readyState属性会根据页面加载的程度,显示不同的值,具体如下
- loading ---- 正在加载
document — 仍在加载。
interactive — 可交互 (文档已被解析,"正在加载"状态结束,但是子资源仍在加载(如图像,样式表和框架之类的)
complete— 完成文档和所有子资源已完成加载。
- 写一个判断,当页面的加载状态为完成时(值为complete),便获取到懒加载的div,将类名设置为none,显示主要页面。
全部代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<style>
*{
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
#loadingContainer {
position: fixed;
width: 100%;
height: 100%;
background: black;
z-index: 1;
top: 0px;
left: 0px;
color: #ffffff;
}
#loadingContainer div {
text-align: center;
width: 300px;
height: 100px;
margin: auto;
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}
.none {
display: none;
}
</style>
</head>
<body>
<div id="loadingContainer">
<div>
<p>系统初始化中请稍后...</p>
</div>
</div>
<div id="app"></div>
<script type="text/javascript">
(function init(){
document.onreadystatechange = ()=>{
if(document.readyState == "complete")
document.querySelector('#loadingContainer').className = "none";
}
})()
// ({ 这个写法也可以
// init:()=>{
// document.onreadystatechange = ()=>{
// if(document.readyState == "complete")
// document.querySelector('#loadingContainer').className = "none";
// }
// }
// }).init()
</script>
</body>
</html>
效果图: