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

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

简介

通常用 Vue.js 编写单页应用(SPA)时,当加载页面时,所有必需的资源(如 JavaScript 和 CSS 文件)都会被一起加载。在处理大文件时,这可能会导致用户体验不佳。

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

[[348453]]

为什么要按需加载?

Vue.js 中 SPA 的典型工作方式是将所有功能和资源打包一并交付,这样可以使用户无需刷新页面即可使用你的应用。如果你没有为了按需加载页面针对自己的应用进行明确的设计,那么所有的页面会被立即加载,或者提前使用大量内存进行不必要的预加载。

这对有许多页面的大型 SPA 非常不利,会导致使用低端手机和低网速的用户体验会很差。如果通过按需加载,用户将不需要下载他们当前不需要的资源。

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

准备项目

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

事件总线是一个 Vue 实例的单例。由于所有 Vue 实例都有一个使用 $on和 $emit的事件系统,因此可以用它在应用中的任何地方传递事件。

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

  1. import Vue from 'vue' 
  2. export default new Vue() 

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

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

添加路由和页面

用 npx 安装 Vue router 并使用:

  1. $ npx vue add router 

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

以下默认配置:

  1. import About from '../views/About.vue' 
  2.     path: '/about', 
  3.     name: 'About', 
  4.     component: About 
  5. }, 

将其改为:

  1.     path: '/about', 
  2.     name: 'About', 
  3.     component: () => import('../views/About.vue') 
  4. }, 

如果希望可以选择按需加载某些页面,而不是全局禁用预取和预加载,可以用特殊的 Webpack 注释,不要在 vue.config.js 中配置 Webpack:

  1. import( 
  2.     /* webpackPrefetch: true */ 
  3.     /* webpackPreload: true */ 
  4.     '../views/About.vue' 

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

实现进度条

由于无法准确估算页面的加载时间(或完全加载),因此我们无法真正的去创建进度条。也没有办法检查页面已经加载了多少。不过可以创建一个进度条,并使它在页面加载时完成。

由于不能真正反映进度,所以描绘的进度只是进行了随机跳跃。

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

  1. $ npm i lodash.random 

然后,创建一个 Vue 组件 components/ProgressBar.vue:

  1. <template> 
  2.     <div :class="{'loading-container': true, loading: isLoading, visible: isVisible}"> 
  3.         <div class="loader" :style="{ width: progress + '%' }"> 
  4.             <div class="light"></div> 
  5.         </div> 
  6.         <div class="glow"></div> 
  7.     </div> 
  8. </template> 

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

  1. <script> 
  2. import random from 'lodash.random' 
  3. import $eventHub from '../components/eventHub' 
  4. </script> 

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

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

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

  1. export default { 
  2.     name: 'ProgressBar', 
  3.      
  4.     data: () => ({ 
  5.         isLoading: true, // 加载完成后,开始逐渐消失 
  6.         isVisible: false, // 完成动画后,设置 display: none 
  7.         progress: startingPoint, 
  8.         timeoutId: undefined, 
  9.     }), 
  10.  
  11.     mounted() { 
  12.         $eventHub.$on('asyncComponentLoading', this.start) 
  13.         $eventHub.$on('asyncComponentLoaded', this.stop) 
  14.     }, 
  15.  
  16.     methods: { 
  17.         start() { 
  18.             this.isLoading = true 
  19.             this.isVisible = true 
  20.             this.progress = startingPoint 
  21.             this.loop() 
  22.         }, 
  23.  
  24.         loop() { 
  25.             if (this.timeoutId) { 
  26.                 clearTimeout(this.timeoutId) 
  27.             } 
  28.             if (this.progress >= endingPoint) { 
  29.                 return 
  30.             } 
  31.             const size = (endingPoint - startingPoint) / (defaultDuration / defaultInterval) 
  32.             const p = Math.round(this.progress + random(size * (1 - variation), size * (1 + variation))) 
  33.             this.progress = Math.min(p, endingPoint) 
  34.             this.timeoutId = setTimeout
  35.                 this.loop, 
  36.                 random(defaultInterval * (1 - variation), defaultInterval * (1 + variation)) 
  37.             ) 
  38.         }, 
  39.  
  40.         stop() { 
  41.             this.isLoading = false 
  42.             this.progress = 100 
  43.             clearTimeout(this.timeoutId) 
  44.             const self = this 
  45.             setTimeout(() => { 
  46.                 if (!self.isLoading) { 
  47.                     self.isVisible = false 
  48.                 } 
  49.             }, 200) 
  50.         }, 
  51.     }, 

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

最后其添加一些样式:

  1. <style scoped> 
  2. .loading-container { 
  3.     font-size: 0; 
  4.     position: fixed; 
  5.     top: 0; 
  6.     left: 0; 
  7.     height: 5px; 
  8.     width: 100%; 
  9.     opacity: 0; 
  10.     display: none; 
  11.     z-index: 100; 
  12.     transition: opacity 200; 
  13.  
  14. .loading-container.visible { 
  15.     display: block; 
  16. .loading-container.loading { 
  17.     opacity: 1; 
  18.  
  19. .loader { 
  20.     background: #23d6d6; 
  21.     display: inline-block; 
  22.     height: 100%; 
  23.     width: 50%; 
  24.     overflow: hidden; 
  25.     border-radius: 0 0 5px 0; 
  26.     transition: 200 width ease-out; 
  27.  
  28. .loader > .light { 
  29.     float: right; 
  30.     height: 100%; 
  31.     width: 20%; 
  32.     background-image: linear-gradient(to right, #23d6d6, #29ffff, #23d6d6); 
  33.     animation: loading-animation 2s ease-in infinite; 
  34.  
  35. .glow { 
  36.     display: inline-block; 
  37.     height: 100%; 
  38.     width: 30px; 
  39.     margin-left: -30px; 
  40.     border-radius: 0 0 5px 0; 
  41.     box-shadow: 0 0 10px #23d6d6; 
  42.  
  43. @keyframes loading-animation { 
  44.     0% { 
  45.         margin-right: 100%; 
  46.     } 
  47.     50% { 
  48.         margin-right: 100%; 
  49.     } 
  50.     100% { 
  51.         margin-right: -10%; 
  52.     } 
  53. </style> 

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

  1. <template> 
  2.     <div> 
  3.         <progress-bar></progress-bar> 
  4.         <router-view></router-view> 
  5.         <!--- 你的其它组件 --> 
  6.     </div> 
  7. </template> 
  8.  
  9. <script> 
  10. import ProgressBar from './components/ProgressBar.vue' 
  11. export default { 
  12.        components: { ProgressBar }, 
  13. </script> 

然后你就可以在页面顶端看到一个流畅的进度条:

页面顶端的进度条

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

  1. import $eventHub from '../components/eventHub' 
  2.  
  3. router.beforeEach((to, from, next) => { 
  4.     if (typeof to.matched[0]?.components.default === 'function') { 
  5.         $eventHub.$emit('asyncComponentLoading', to) // 启动进度条 
  6.     } 
  7.     next() 
  8. }) 
  9.  
  10. router.beforeResolve((to, from, next) => { 
  11.     $eventHub.$emit('asyncComponentLoaded') // 停止进度条 
  12.     next() 
  13. }) 

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

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

总结

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

 

责任编辑:赵宁宁 来源: 前端先锋
相关推荐

2024-04-01 08:18:52

CSSHTMLWeb

2015-07-31 11:19:43

数字进度条源码

2020-04-07 09:43:17

vue.js进度组件开发

2023-07-18 15:49:22

HTMLCSS

2021-11-02 15:35:01

JavaScriptCSS开发

2021-04-28 10:01:00

JSCSS进度条

2022-02-04 21:33:34

Ajaxjs网站

2020-11-02 18:27:29

进度条Linuxcp

2011-07-05 15:16:00

QT 进度条

2015-08-03 11:39:20

拟物化进度条

2013-03-12 10:35:06

CSS 3

2015-01-12 09:30:54

Android进度条ProgressDia

2015-01-12 12:13:03

Android进度条ProgressDia

2022-07-20 09:10:47

Linux

2012-01-17 13:58:17

JavaSwing

2009-06-06 18:54:02

JSP编程进度条

2023-12-11 17:15:05

应用开发波纹进度条ArkUI

2012-07-31 09:53:33

HTML5进度条

2010-01-25 18:27:54

Android进度条

2020-12-14 13:32:40

Python进度条参数
点赞
收藏

51CTO技术栈公众号