Open In App

Lazy Loading Components in VueJS

Last Updated : 21 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Lazy Loading, fundamentally, is a design principle that delays the initialization of an object or a resource until the point at which it is genuinely required. The purpose of lazy loading is to postpone downloading parts of the application that are not needed by the user on the initial page load which ends up in much better loading time.

As a app scales, the compiled JavaScript bundle file will keeps on increasing and thus affect the page load time. With the help of the defineAsyncComponent method, we can only load a component if and when needed.

Setting Up the Project Environment

Step 1: Create a Vue.js application

npm create vue@latest

Step 2: Navigate to your project directory and install dependencies

cd your-project-name && npm install

Project Structure:

Screenshot_2023-09-27-09-28-23_1920x1080
Project Structure

Example: Lazy Loading a Component, We can use the new defineAsyncComponent function. We need to do is pass a function that loads the components. As we are loading the GFG component later there may be a short delay while the lazy-loaded part of UI is being requested and rendered for that pass in a loading component property which will be displayed while the component is being loaded.

JavaScript
<script setup>
    // lazy load the component
    import Loading from './components/Loading.vue'
    import { defineAsyncComponent } from 'vue';
    import { ref } from 'vue';
    const GFG = defineAsyncComponent({
        loader: () => import('./components/GFG.vue'),
        loadingComponent: Loading
    });
    const show = ref(false);
    const toggle = () => show.value = !show.value;
</script>

<template>
    <div>
        <button @click="toggle">Toggle</button>
        <GFG v-if="show" />
    </div>
</template>
JavaScript
<!-- GFG.vue -->
<template>
    <!-- a centered align image -->
    <img src=
"https://media.geeksforgeeks.org/gfg-gg-logo.svg" 
         alt="GeeksforGeeks"
         style="display: block;
                margin-left: auto;
                margin-right: auto;">
</template>
JavaScript
<!-- Loading.vue -->

<template>
    <div class="loading">
        <div class="loading__spinner"></div>
    </div>
</template>
<style>
    .loading {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
    }
    .loading__spinner {
        width: 50px;
        height: 50px;
        border: 5px solid #f3f3f3;
        border-top: 5px solid #2f8d46;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
</style>

Output:


Next Article

Similar Reads