search
HomeWeb Front-endVue.jsImplement Vue lazy loading with progress bar

Implement Vue lazy loading with progress bar

Oct 28, 2020 pm 05:36 PM
javascriptvue.jsfront end

The followingVue.js column will introduce to you how to add a progress bar to Vue's lazy loading. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Implement Vue lazy loading with progress bar

Introduction

Usually when writing a single page application (SPA) with Vue.js, when the page is loaded, all required resources (such as JavaScript and CSS files) will be loaded together. This can lead to a poor user experience when working with large files.

With Webpack, you can load pages on demand in Vue.js using the import() function instead of the import keyword.

Why load on demand?

The typical way SPA works in Vue.js is to package all functions and resources and deliver them together, so that users can use your application without refreshing the page. If you don't explicitly design your application to load pages on demand, all pages will be loaded at once, or a large amount of memory will be used in advance for unnecessary preloading.

This is very detrimental to large SPA with many pages, and will lead to poor user experience using low-end mobile phones and low network speeds. With on-demand loading, users won't need to download resources they don't currently need.

Vue.js does not provide any loading indicator related controls for dynamic modules. Even if prefetching and preloading are performed, there is no corresponding space to let the user know the loading process, so it is necessary to improve the user experience by adding a progress bar.

Preparing the project

First you need a way for the progress bar to communicate with Vue Router. Event bus mode is more suitable.

The event bus is a singleton of a Vue instance. Since all Vue instances have an event system using $on and $emit, you can use this to deliver events anywhere in your application.

First create a new file eventHub.js in the components directory:

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

Then configure Webpack to disable prefetching and preloading, This allows you to do this on a per-function basis, or you can disable it globally. Create a vue.config.js file in the root folder and add the relevant configuration to disable prefetching and preloading:

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

Add routes and pages

Use npx Install Vue router and use:

$ npx vue add router

Edit the router file located under router/index.js and update the route so that it can be used import() Function instead of import statement:

The following default configuration:

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

Change it to:

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

If you want, you can choose to load something on demand Instead of disabling prefetching and preloading globally for some pages, you can use special Webpack annotations and do not configure Webpack in vue.config.js:

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

import() The main difference between and import is that ES modules loaded by import() are loaded at runtime and ES modules loaded by import are loaded at compile time ES modules. This means that you can use import() to delay the loading of modules and load them only when necessary.

Implementing the progress bar

Because we cannot accurately estimate the loading time (or complete loading) of the page, we cannot real create a progress bar. There is also no way to check how much the page has loaded. But you can create a progress bar and have it complete when the page loads.

Since it cannot truly reflect progress, the progress depicted is just a random jump.

Install lodash.random first, because this package will be used to generate some random numbers during the process of generating the progress bar:

$ npm i lodash.random

Then, create a Vue componentcomponents/ProgressBar.vue:

<template>
    <p>
        </p>
<p>
            </p>
<p></p>
        
        <p></p>
    
</template>

Next add a script to the component. First import random and $eventHub in the script, which will be used later:

<script>
import random from &#39;lodash.random&#39;
import $eventHub from &#39;../components/eventHub&#39;
</script>

After importing, define some variables in the script that will be used later:

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

Then code the logic to implement asynchronous loading of components:

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)
        },
    },
}

In the mounted() function, use the event bus to listen to the loading of asynchronous components. Once the route tells us we've navigated to a page that hasn't loaded yet, it will start the loading animation.

Finally add some styling:

<style>
.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>

Finally add the ProgressBar to App.vue or the layout component as long as it is located with the route view Just in the same component, it is available throughout the life cycle of the application:

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

<script>
import ProgressBar from &#39;./components/ProgressBar.vue&#39;
export default {
       components: { ProgressBar },
}
</script>

Then you can see a smooth progress bar at the top of the page:

Implement Vue lazy loading with progress bar

Trigger progress bar for lazy loading

NowProgressBar is listening on the event bus for asynchronous component loading events. An animation should be triggered when certain resources are loaded this way. Now add a route guard to the route to receive the following events:

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 应用中的预取和预加载功能,并创建了一个进度条组件,该组件可显示以模拟加载页面时的实际进度。

原文:https://stackabuse.com/lazy-loading-routes-with-vue-router/

作者:Stack Abuse

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Implement Vue lazy loading with progress bar. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

How to implement component jump for vueHow to implement component jump for vueApr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

How to jump to the div of vueHow to jump to the div of vueApr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use