Importing dynamically divides the code without implementing lazy loading

I am exploring the implementation of lazy loading in Vue Router to ensure that certain parts of the code are only loaded when they are needed.

Following the guidelines from the official documentation on Lazy Loading in Vue Router available at: https://router.vuejs.org/en/advanced/lazy-loading.html

To test this, I made changes to how the Vault module is imported in my router file:

import Vue from 'vue';
import Router from 'vue-router';

// Containers
import Full from '@/containers/Full';

// Views
// TODO: views should be imported dynamically
import Dashboard from '@/views/Dashboard';
const Vault = () => import('@/views/Vault');
import Page404 from '@/views/Page404';
import Page500 from '@/views/Page500';
import Login from '@/views/Login';

Vue.use(Router);

export default new Router({
    routes:         [
        {
            path:      '/',
            redirect:  '/dashboard',
            name:      'VENE',
            component: Full,
            children:  [
                {
                    path:      'dashboard',
                    name:      'dashboard',
                    component: Dashboard
                },
                {
                    path:      'vault',
                    name:      'vault',
                    component: Vault
                },
            ],
        },
        {
            path:      '/login',
            name:      'Login',
            component: Login,
        },
        {
            path:      '/404',
            name:      'Page404',
            component: Page404,
        },
        {
            path:      '/500',
            name:      'Page500',
            component: Page500,
        },
    ],
});

Everything seemed to be working fine, however, upon initial page load, the extracted bundle that was supposed to be lazily loaded actually loads upfront:

https://i.sstatic.net/PeiMc.jpg

Subsequently, when navigating to that view using the router, it appears again in the Dev Tools Network Tab but shows that it's loaded from the disk, indicating that the bundle is being loaded on the first page visit, contradicting the concept of lazy loading.

Answer №1

The reasons behind this issue are twofold. It appears that you have properly configured lazy-loading for the Vault component. One useful tip is to specify the webpack chunk name in the dynamic import statement:

const Vault = () => import(/* webpackChunkName: "vault" */ '@/views/Vault')

This will label the chunk in your network tab as "vault"

Firstly, it seems likely that you are using @vue-cli based on your folder structure and use of the /src alias. When setting up your project with @vue-cli, depending on your choices, a webpack configuration is used for progressive web apps that prefetches all resources as explained here. While browsers prioritize these downloads, some prefetching may seem to block other resources. The advantage of prefetching is utilizing idle browser time to cache resources that might be needed later by users who do not support service workers.

Secondly, there are ways to disable the prefetch plugin provided by @vue-cli. You can customize the default configuration by adding or editing the vue.config.js file at the root of your project.

courtesy @LinusBorg 

// vue.config.js
chainWebpack: (config) => {

  // A, remove the plugin
  config.plugins.delete('prefetch')

  // or:
  // B. Alter settings:
  config.plugin('prefetch').tap(options => {
    options.fileBlackList.push([/myasyncRoute(.)+?\.js$/])
    return options
  })
}

-- Make sure to choose either option A or option B; not both. --

Reference: https://github.com/vuejs/vue-cli/issues/979

I've personally had success with option A, but I recommend testing and evaluating the results yourself to determine the best approach for your users and application.

I admire the customizability of @vue-cli in various situations like this. It's worth exploring to tailor your app according to your preferences rather than adhering strictly to predefined configurations.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is mastering canvas games a worthwhile pursuit?

Being passionate about creating a canvas game, I have some doubts about whether it's worth the effort. Here's why... With Adobe Flash, you can create highly complex animations, games, and apps. It makes me wonder if there will soon be a program ...

Passing the $scope variable between functions

Here is the function in my angular controller: $scope.selectinteresteduser = function(Id){ $scope.selecteduserid = Id; } $scope.sendMessageToEmployeer = function($scope.selecteduserid) { alert($scope.selecteduserid); } I am looking for a way to pa ...

Transferring token values between collections in POSTMAN - AUTOMATION | NEWMAN: A step-by-step guide

My goal is to streamline my unit test cases by utilizing the POSTMAN Collections API & NEWMAN. I successfully created two test cases that are performing as expected. Upon exporting the collection from POSTMAN, I proceed to generate the test report using NE ...

"Can someone help me figure out where I went wrong with my eventBus

I need to call a function from a different component that is not in a parent-child relationship. I attempted to use eventbus, but I am unsure if I have implemented it correctly as the function is not working. I created a boot file named eventBus.js and add ...

Utilizing Typescript to bind the 'this' keyword to array sorting

Currently, I am transitioning a functional JS solution to Typescript. In my possession is an array of objects containing geolocation data in the form of latitude and longitude coordinates. My goal is to arrange these objects based on their proximity to a ...

Why isn't my named function functioning properly in node.js?

Trying my hand at creating an HTTP server using node.js. This code snippet is successful: const http = require('http'); const server = http.createServer((req, res) => { console.log(req.url); res.end('Hello Node.js'); }); server.lis ...

unable to retrieve / interpret data from herdsmen using fetch

When sending a request to a node server, the server responds with headers and a blank body. Despite being able to view the headers in the network activity panel within dev-tools, I faced difficulties reading them using the following code: let uploaded ...

Can you explain the distinctions between Vue JS and React JS?

As I delve into learning Vue Js and React Js, my search for a detailed comparison between the two on Google left me unsatisfied. I came across resources answering the singular questions "What is Vue js?" and "What is React Js," but none that directly comp ...

Need to obtain the stack trace from the catch block in a request-p

Currently, I am utilizing the 'request-promise' library in my node-js application for making API calls. However, I am facing challenges in obtaining the correct call stack from the 'catch' function. Upon experimenting with it, I discove ...

What is the best way to access a global variable within a store mutation function

I am encountering an issue with the vue-i18n dependency. How can I access the const i18n from main.js in root.js (store)? The technologies I am using include: Vuejs 2.X Latest version of Vue-i18n Vuex for Vuejs 2.X In main.js (vue-cli) Vue.use(VueI18 ...

JavaScript eliminates any existing CSS styling

I am new to the world of web development and recently created a sample webpage. The page consists of an HTML file, a CSS file, and a JavaScript file. However, I encountered an issue where linking the JavaScript file to the HTML page caused the CSS formatti ...

Is it advisable to clear the bootstrap tooltips array in order to conserve browser memory once I have finished rendering new tooltips?

My apologies if this question has been asked before, but I searched online first and couldn't find a helpful answer. Beautiful Views Recently, I was working on a project where I needed to display search results, each accompanied by a button that trig ...

Switching between tabs in Angular changes the URL

I am working on a tab component and here is the code for it: <body ng-app="components"> <h3>BootStrap Tab Component</h3> <tabs> <pane title="First Tab"> <div>This is the content of the first tab.</div&g ...

Filter the output from a function that has the ability to produce a Promise returning a boolean value or a

I can't help but wonder if anyone has encountered this issue before. Prior to this, my EventHandler structure looked like: export interface EventHandler { name: string; canHandleEvent(event: EventEntity): boolean; handleEvent(event: EventEntity ...

Inform the parent Vue container of the starting value

I have set up a Vue container with radio button inputs: <template lang='pug'> each v in [ 1, 500, 1000 ] input( v-model='value', value=v ) label( for=v ) </template> <script lang='ts'> ...

Having trouble getting the node serialport module to function properly when using the child process fork()

My current project involves implementing an asynchronous read in USB using fork() from the child_process module in electron. Essentially, upon clicking a div (id="read"), a message is sent from the renderer process to the main process. The main process the ...

Completing a fetch promise and sending the outcome to a function that is not awaited

I have a function that retrieves data from a Postgresql database and returns it. The expected behavior is to fetch the data using the async function getCat(), process it in const Catalogue, and then return it to a ReactJS component. catalogue.tsx: import ...

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

Is the DOMContentLoaded event connected to the creation of the DOM tree or the rendering tree?

After profiling my app, I noticed that the event is triggered after 1.5 seconds, but the first pixels appear on the screen much later. It seems like the event may only relate to DOM tree construction. However, this tutorial has left me feeling slightly con ...

Struggling to change the div content with ajax response transmitted through php

I would like to apologize in advance if this question has already been addressed elsewhere. After conducting a search, I came across several relevant posts that have guided me to this point. Below is the form snippet containing 1 input box, a button, and ...