Vuejs Performance: Lazy loading and code splitting in Vue.js(part 1)

Tram Ho

Keeping your apps from loading fast is getting harder and harder. In this series, I’ll go into depth with Vue performance optimization techniques that you can use in your Vue.js applications to make them load instantly and work smoother. My goal is to make this series a complete and complete guide to Vue application performance.

How does Webpack pack (bundling)?

Most of the tips in this series will focus on making our JS bundle (bundle) smaller. To understand what’s important, we need to first understand how Webpack encapsulates all of our files.

While wrapping our assets (folder containing our app’s css, icons, images), Webpack is creating something called a dependency graph . It’s the graph that associates all of our files based on imports. Assuming we have a file main.js designated as the entry point ( entry point : which is first accessed when running the app) in our webpack configuration, which will be the root of the dependency graph. Now every module js that we will import in this file becomes its node in the diagram and every module imported in these nodes becomes its node.

Webpack is using this dependency chart to detect which file it should include in the output bundle . The output package is just a single js file (or more as we will see in the following sections) that contains all the modules from the dependency diagram.

This package is basically our entire JavaScript application.

We can illustrate this process with the following image:

Now that we know how to package (budling) of webpack, it is clear that the bigger our project, the bigger the initial JavaScript package.

The larger the package, the longer it takes to download and parse the user. The longer a user waits, the more likely they are to leave our site. In fact, according to Google, 53% of mobile users leave a page in more than 3 seconds to load.

In short, a bigger package = fewer users ( bigger bundle = fewer users ), which can directly lead to a loss of potential revenue. Bing is a prime example – a 2 second delay cost them 4.3% of their revenue per visitor.

Lazy loading

So how can we trim the package size when we still need to add new features and improve our application? The answer is yes – lazy loading and code splitting .

As the name suggests lazy loading is the process of lazily loading parts of your application. In other words – download them only when we really need them. Code splitting is just the process of splitting an application into these slowly loaded parts

In most cases, you don’t need all the code from the javascript bundle (javascript bundle) immediately when a user visits your website.

For example, we don’t need to dedicate valuable resources to load the ” My Page ” area for our first time visitors. Or there may be modals, tooltips and other unnecessary parts and components on every page.

The lazy loading feature allows us to split the package and deliver only the necessary parts so that users don’t waste time downloading and parsing unused code.

To see how much JavaScript is actually used in our site, we can go to devtools (F12) -> Coverage -> press the reload icon right below (with chrome). Now, we should be able to see how much code has downloaded and actually used.

Everything marked in red is unnecessary on the current route and can be lazy loaded . If you are using the source map, you can click on any file in this list and see which part of the file is not in use. As we can see, even vuejs.org has a lot of points for improvement.

By lazy loading the appropriate components and libraries, this is probably the easiest way to increase performance.

Ok, we already know what lazy loading is and how useful it is. Please use it in your Vue app

Dynamic Import

We can easily load some parts of the application lazily with wepack dynamic imports . Let’s see how they work and how they differ from regular imports .

If we import a js module with a standard way like this:

It will be appended as a node of main.js in the dependency chart and bundled .

But what if we only need our Cat module in certain cases like feedback to user interaction? Wrapping this module with our initial bundle is a bad idea since it’s not needed all the time. We need a way to tell our app when it will download this code.

This is where dynamic imports can help us! See this example:

Take a quick look at what happened here:

Instead of importing the Cat module directly, we created a function that returns the import () function. Now webpack will package ( bundle ) the contents of the dynamically imported module into a separate file . The function representing the dynamically imported module returns a Promise that will give us access to the module ‘s exported members when resolved .

We can then download this optional snippet later, as needed. For example, response to a certain user interaction (like route change or mouse click).

By doing dynamic import, we are essentially isolating the given node (in that case Cat ) that will be added to the dependency chart and downloading this part when we decide it’s necessary (they are We are also cutting out the modules imported inside Cat.js ).

Let’s look at another example that will better illustrate this mechanism.

Let’s say we have a very small online store with 4 files:

  • main.js : main package (main bundle).
  • product.js : contains the scripts of the product page.
  • productGallery.js : contains the scripts of the product page page.
  • category.js : contains the scripts of the category page.

Without going into too much detail, let’s take a look at how those files are distributed across the application:

In the code above, depending on the current route , we are dynamically importing the product or category module and then running the init function exported by both.

Given how dynamic import works, we know that product and category will end up in a separate bundles but what happens to the productGallery module that is not dynamically imported? As we already know how to dynamically import the module, we are trimming part of the dependency chart. Everything that is imported into this section will be grouped together so that productGallery is packaged with the product module.

In other words, we are just creating some kind of new entry point for the dependency chart.

Lazy loading Vue components

Now we know what lazy loading is and why we need it. It’s time to see how we can use it in our Vue applications.

This is super easy and we can lazily load the entire Single Page Component , with its CSS and HTML with the same syntax as before!

… that’s all you need! Components will now be downloaded only when required. Here are the most common ways to invoke dynamic loading of Vue components:

  • Call the imported function:

  • Components required to render:

Please note that calling lazyComponent function will only happen when the requested element is displayed in a template. For example:

The component will not load until it is requested in the DOM, as soon as the v-if value changes to true .

Thank you for watching, watch the sequels. Translated from vueschool

Share the news now

Source : Viblo