exp1. 同步加载远程js脚本阻塞页面渲染
<html>
<head>
<style>
.container {
border: 1px solid gray;
margin: auto;
max-width: 600px;
height: 600px;
display: grid;
grid-template-columns: repeat(6, 1fr);
grid-template-rows: repeat(6, 1fr);
}
.container>div {
display: inline;
background-color: pink;
box-sizing: border-box;
}
.container>div:nth-child(1) {
grid-column-start: 2;
grid-column-end: 4;
grid-row-start: 2;
grid-row-end: 4;
margin-right: 2px;
}
img.err {
display: none;
}
</style>
<script src="https://cdn.bootcss.com/vue/2.6.1/vue.min.js"></script>
</head>
<body>
<script>
console.log(2)
</script>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<script>
console.log(3)
</script>
</body>
</html>
实验思路:使用bootcdn加载vue,使用chrome浏览器network面板,调整网络速度,我这里自定义了一个下载速度为1kb,并延迟3000ms的选项(very slow),并使用它
刷新页面,观察网络资源,当主页面1.html记载完,vue.min.js 状态还是pending的时候,发现页面空白,脚本加载完成,页面显示了。
以下为贴图展示:
1. 脚本pending时,【页面没有渲染,控制台没有打印】
2.脚本加载finish( 或者失败时 )时 【页面渲染了,并且控制台打印了】
exp2 script的执行会阻塞页面渲染
将加载vue的那段script 替换为如下脚本,执行一个会阻塞主线程的alert弹框,并且不点击
<script>
alert()
</script>
截图如下
发现scritp的执行同样会阻塞 页面渲染,且没有打印,
可以归纳出 script的一些特性了,并在开发中注意这些问题。
这里我给个想法:
当前web/移动端h5页面 很火的一个概念叫做“骨架屏”,其实就是页面内容还未加载完毕(比如用户请求数据并渲染到view,请求还未返回时,为了一个得到较好的用户体验(而不是盯着白板无聊的等待)的一种技术,还有个概念就是模块加载。
结合前文的实验,如果我们有个主模块(一个js文件),用来加载其他的js模块文件,那么要达到用户加载完某html页面的时候可以立即显示出一个骨架屏,我们可以将这个主模块js文件,放置到</body>后来,让骨架优先渲染出来,此时再去加载js文件