Lazy Loading Routes in Vue Router
Last Updated :
27 Sep, 2024
Lazy Loading Routes refer to a way of developing web applications in which it is possible to optimize performance improvement concerning loading. Instead of loading a whole application at once, lazy loading will allow parts of the app, such as specific routes or components, to load only when needed. This reduces the initial load time and hence improves performance, especially for large applications.
How Lazy Loading Works in Vue?
In a common application, routes and components load together; thus, the initial load is heavy and slow. In the case of lazy loading, every route or component is loaded only when the user navigates to this route.
For example, imagine your application has lots of pages, here understood as a route. Each of the pages can be lazy-loaded; meaning, it will just run what's necessary code in the current page. You then navigate to another route and automatically load up that particular page's code.
Steps to implement Lazy Load Routes
Step 1: Set Up Your Vue Project
If you don’t have an already created Vue.js project, you can create na w project using Vue CLI. This command can also be used to create a vite project.
npm create vue@latest
Project creationStep 2: Navigate to the project's root directory:
cd lazyloadingexample
Step 3: To install all packages, run this command:
npm install
Step 4: If Vue Router is not already installed, install it in your project:
npm install vue-router
Step 5: Run this command to execute the Project:
npm run dev
Project Structure:
Updated Dependencies:
"dependencies": {
"pinia": "^2.1.7",
"vue": "^3.4.29",
"vue-router": "^4.4.5"
}
Implementation of Lazy loading in Webpack and Vite are different. Let’s see how to set up lazy loading using both metods:
Using Webpack
Webpack in Vue.js refers to the tool that bundles all your project files, including JavaScript and CSS files, images, and so on, into fewer files, which the browser will load. It helps manage files enormously, reduces loads time, and encourages features like Vue components, code splitting, and hot module replacement (auto-refresh during coding). It helps build fast and efficient applications with Vue.js, particularly in production.
Syntax:
const Components_name= () => import(/* webpackChunkName: "Chunk_name" */ '../views/Components_name.vue');
Example: This example demonstrates lazy loading using Webpack.
JavaScript
//src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'Home',
component: () => import(/* webpackChunkName: "main" */ '../views/HomeView.vue')
},
{
path: '/about',
name: 'About',
component: () => import(/* webpackChunkName: "main" */ '../views/AboutView.vue')
}
]
})
export default router
JavaScript
//src/App.vue
<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
</script>
<template>
<header>
<div class="wrapper">
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
</div>
</header>
<RouterView />
</template>
JavaScript
//src/main.ts
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
Output:
Using vite
Vite in Vue.js is a fast build tool which creates and bundles your app files for development and production. It is faster than Webpack as it only processes the files you are actually working on. It supports Vue components, hot module replacement (hot updates while coding), and gives faster loading times with easier configuration, making it really easy to develop and optimize Vue apps.
Syntax:
const ComponentName = () => import('path/to/your/component');
Example: This Example is used to demonstrate the configuration of lazy loading with Vite.
JavaScript
// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'Home',
component: () => import('../views/HomeView.vue')
// Lazy load HomeView.vue
},
{
path: '/about',
name: 'About',
component: () => import('../views/AboutView.vue')
// Lazy load AboutView.vue
}
]
})
export default router
JavaScript
//vite.config.ts
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
vueJsx(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
build: {
rollupOptions: {
output: {
// Group components into the same chunk
manualChunks(id) {
'main';['../views/HomeView.vue', '../views/AboutView.vue']
}
}
}
}
}
)
JavaScript
// src/App.vue
<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
</script>
<template>
<header>
<div class="wrapper">
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
</div>
</header>
<RouterView />
</template>
JavaScript
// src/main.ts
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
Output:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read