浅析JS异步加载进度条
一、前言
异步加载(Async Loading)已成为一个前端性能优化点,webpack做内部打包时自动对异步进行按需加载,并做了很多优化点。而进度条是主流的展示加载进度的方式之一,那么在HTML页面使用异步加载做进度条的展示时,该如何处理呢?下面是本人介绍的示例。
二、实现思路
- 加载异步组件时,先加载进度条组件
- 获取异步加载的总文件数量,通过动态修改进度条组件的宽度来呈现当前加载进度
三、实现过程
以Vue为例子,假设你需要加载三个组件,这三个组件分别是 a.vue
、b.vue
、c.vue
,那么示例代码如下:
<template>
<div id="app">
<progress-bar :percent="percent"/>
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>
</template>
<script>
import ProgressBar from './components/ProgressBar.vue'
export default {
components: {
ProgressBar
},
data () {
return {
percent: 0, // 进度条百分比
count: 0, // 已加载文件数量
total: 0 // 总文件数量
}
},
beforeRouteEnter (to, from, next) {
// 加载异步组件之前,先加载进度条组件
const loadingInstance = this.$loading({
lock: true,
text: 'Loading',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
})
// 获取异步加载的总文件数量
const matches = to.matched.reduce((prev, curr) => prev.concat(curr.components.default), [])
this.total = matches.length
// 将计算百分比的方法挂载到loading实例上
loadingInstance.calculatePercent = () => {
this.percent = Math.floor(++this.count / this.total * 100)
if (this.percent >= 100) {
setTimeout(() => {
loadingInstance.close()
}, 800)
}
}
// 在loading实例中同步进度条进度
loadingInstance.syncProgressBar = () => {
loadingInstance.calculatePercent()
if (this.percent < 100) {
setTimeout(() => {
loadingInstance.syncProgressBar()
}, 200)
}
}
// 加载异步组件
Promise.all(matches.map(component => {
return component()
})).then(() => {
loadingInstance.calculatePercent()
})
}
}
</script>
四、示例说明
示例1:
在等待加载资源的页面或页面插件中加入进度条展示,增强用户体验,方便用户知道还需要等待多长时间。
示例2:
假设本地代码都已经做了很好的打包和拆分优化工作,在该文方法的基础上,用户使用了外部资源,在外部资源加载完成之前,页面进度条会呈现加载状态,并配合提示语展示当前状态,帮助用户评估资源加载总体时间,减少异常停留的时间。
五、总结
JS异步加载进度条,这篇文章主要介绍了如何使用JavaScript引入异步组件时,在加载组件之前先加载进度条组件,并动态修改进度条组件的宽度来呈现当前加载进度。以上示例也许不能完全满足你的需求,但是基本思路是值得学习的,你可以根据自己的需求进行改造。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:浅析JS异步加载进度条 - Python技术站