为 Vue 的惰性加载加一个进度条

做者:Stack Abuse

翻译:疯狂的技术宅javascript

https://stackabuse.com/lazy-l...html

未经容许严禁转载前端

简介

一般用 Vue.js 编写单页应用(SPA)时,当加载页面时,全部必需的资源(如 JavaScript 和 CSS 文件)都会被一块儿加载。在处理大文件时,这可能会致使用户体验不佳。vue

借助 Webpack,能够用 import() 函数而不是 import 关键字在 Vue.js 中按需加载页面。java

为何要按需加载?

Vue.js 中 SPA 的典型工做方式是将全部功能和资源打包一并交付,这样可使用户无需刷新页面便可使用你的应用。若是你没有为了按需加载页面针对本身的应用进行明确的设计,那么全部的页面会被当即加载,或者提早使用大量内存进行没必要要的预加载。webpack

这对有许多页面的大型 SPA 很是不利,会致使使用低端手机和低网速的用户体验会不好。若是经过按需加载,用户将不须要下载他们当前不须要的资源。程序员

Vue.js 没有为动态模块提供任何加载指示器相关的控件。即便进行了预取和预加载,也没有对应的空间让用户知道加载的过程,因此还须要经过添加进度条来改善用户体验。web

准备项目

首先须要一种让进度条与 Vue Router 通讯的方法。事件总线模式比较合适。面试

事件总线是一个 Vue 实例的单例。因为全部 Vue 实例都有一个使用 $on$emit 的事件系统,所以能够用它在应用中的任何地方传递事件。vue-router

首先在 components 目录中建立一个新文件 eventHub.js

import Vue from 'vue'
export default new Vue()

而后把 Webpack 配置为禁用预取和预加载,这样就能够针对每一个函数单独执行此类操做,固然你也能够全局禁用它。在根文件夹中建立一个 vue.config.js 文件并添加禁用预取和预加载的相关配置:

module.exports = {
    chainWebpack: (config) => {
        // 禁用预取和预加载
        config.plugins.delete('prefetch')
        config.plugins.delete('preload')
    },
}

添加路由和页面

npx 安装 Vue router 并使用:

$ npx vue add router

编辑位于 router/index.js 下的 router 文件并更新路由,以即可以用 import() 函数代替 import 语句:

如下默认配置:

import About from '../views/About.vue'
{
    path: '/about',
    name: 'About',
    component: About
},

将其改成:

{
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
},

若是但愿能够选择按需加载某些页面,而不是全局禁用预取和预加载,能够用特殊的 Webpack 注释,不要在 vue.config.js 中配置 Webpack:

import(
    /* webpackPrefetch: true */
    /* webpackPreload: true */
    '../views/About.vue'
)

import()import 之间的主要区别是在运行时加载由 import() 加载的 ES 模块,在编译时加载由 import 加载的 ES 模块。这就意味着能够用 import() 延迟模块的加载,并仅在必要时加载。

实现进度条

因为没法准确估算页面的加载时间(或彻底加载),所以咱们没法真正的去建立进度条。也没有办法检查页面已经加载了多少。不过能够建立一个进度条,并使它在页面加载时完成。

因为不能真正反映进度,因此描绘的进度只是进行了随机跳跃。

先安装 lodash.random,由于在生成进度条的过程当中将会用这个包产生一些随机数:

$ npm i lodash.random

而后,建立一个 Vue 组件 components/ProgressBar.vue

<template>
    <div :class="{'loading-container': true, loading: isLoading, visible: isVisible}">
        <div class="loader" :style="{ width: progress + '%' }">
            <div class="light"></div>
        </div>
        <div class="glow"></div>
    </div>
</template>

接下来向该组件添加脚本。在脚本中先导入 random$eventHub,后面会用到:

<script>
import random from 'lodash.random'
import $eventHub from '../components/eventHub'
</script>

导入以后,在脚本中定义一些后面要用到的变量:

// 假设加载将在此时间内完成。
const defaultDuration = 8000 
// 更新频率
const defaultInterval = 1000 
// 取值范围 0 - 1. 每一个时间间隔进度增加多少
const variation = 0.5 
// 0 - 100. 进度条应该从多少开始。
const startingPoint = 0 
// 限制进度条到达加载完成以前的距离
const endingPoint = 90

而后编码实现异步加载组件的逻辑:

export default {
    name: 'ProgressBar',
    
    data: () => ({
        isLoading: true, // 加载完成后,开始逐渐消失
        isVisible: false, // 完成动画后,设置 display: none
        progress: startingPoint,
        timeoutId: undefined,
    }),

    mounted() {
        $eventHub.$on('asyncComponentLoading', this.start)
        $eventHub.$on('asyncComponentLoaded', this.stop)
    },

    methods: {
        start() {
            this.isLoading = true
            this.isVisible = true
            this.progress = startingPoint
            this.loop()
        },

        loop() {
            if (this.timeoutId) {
                clearTimeout(this.timeoutId)
            }
            if (this.progress >= endingPoint) {
                return
            }
            const size = (endingPoint - startingPoint) / (defaultDuration / defaultInterval)
            const p = Math.round(this.progress + random(size * (1 - variation), size * (1 + variation)))
            this.progress = Math.min(p, endingPoint)
            this.timeoutId = setTimeout(
                this.loop,
                random(defaultInterval * (1 - variation), defaultInterval * (1 + variation))
            )
        },

        stop() {
            this.isLoading = false
            this.progress = 100
            clearTimeout(this.timeoutId)
            const self = this
            setTimeout(() => {
                if (!self.isLoading) {
                    self.isVisible = false
                }
            }, 200)
        },
    },
}

mounted() 函数中,用事件总线来侦听异步组件的加载。一旦路由告诉咱们已经导航到还没有加载的页面,它将会开始加载动画。

最后其添加一些样式:

<style scoped>
.loading-container {
    font-size: 0;
    position: fixed;
    top: 0;
    left: 0;
    height: 5px;
    width: 100%;
    opacity: 0;
    display: none;
    z-index: 100;
    transition: opacity 200;
}

.loading-container.visible {
    display: block;
}
.loading-container.loading {
    opacity: 1;
}

.loader {
    background: #23d6d6;
    display: inline-block;
    height: 100%;
    width: 50%;
    overflow: hidden;
    border-radius: 0 0 5px 0;
    transition: 200 width ease-out;
}

.loader > .light {
    float: right;
    height: 100%;
    width: 20%;
    background-image: linear-gradient(to right, #23d6d6, #29ffff, #23d6d6);
    animation: loading-animation 2s ease-in infinite;
}

.glow {
    display: inline-block;
    height: 100%;
    width: 30px;
    margin-left: -30px;
    border-radius: 0 0 5px 0;
    box-shadow: 0 0 10px #23d6d6;
}

@keyframes loading-animation {
    0% {
        margin-right: 100%;
    }
    50% {
        margin-right: 100%;
    }
    100% {
        margin-right: -10%;
    }
}
</style>

最后将 ProgressBar 添加到 App.vue 或布局组件中,只要它与路由视图位于同一组件中便可,它在应用的整个生命周期中均可用:

<template>
    <div>
        <progress-bar></progress-bar>
        <router-view></router-view>
        <!--- 你的其它组件 -->
    </div>
</template>

<script>
import ProgressBar from './components/ProgressBar.vue'
export default {
       components: { ProgressBar },
}
</script>

而后你就能够在页面顶端看到一个流畅的进度条:

image.png

为延迟加载触发进度条

如今 ProgressBar 正在事件总线上侦听异步组件加载事件。当某些资源以这种方式加载时应该触发动画。如今向路由添加一个路由守护来接收如下事件:

import $eventHub from '../components/eventHub'

router.beforeEach((to, from, next) => {
    if (typeof to.matched[0]?.components.default === 'function') {
        $eventHub.$emit('asyncComponentLoading', to) // 启动进度条
    }
    next()
})

router.beforeResolve((to, from, next) => {
    $eventHub.$emit('asyncComponentLoaded') // 中止进度条
    next()
})

为了检测页面是否被延迟加载了,须要检查组件是否是被定义为动态导入的,也就是应该为 component:() => import('...') 而不是component:MyComponent

这是经过 typeof to.matched[0]?.components.default === 'function' 完成的。带有 import 语句的组件不会被归为函数。

总结

在本文中,咱们禁用了在 Vue 应用中的预取和预加载功能,并建立了一个进度条组件,该组件可显示以模拟加载页面时的实际进度。

173382ede7319973.gif


本文首发微信公众号:前端先锋

欢迎扫描二维码关注公众号,天天都给你推送新鲜的前端技术文章

欢迎扫描二维码关注公众号,天天都给你推送新鲜的前端技术文章

欢迎继续阅读本专栏其它高赞文章:


相关文章
相关标签/搜索