Let's create a Vue component. It will be the component that we will load asynchronously. The content is not important, since we only want to show it.
Let's just write hello from Async. Now, let's register the component globally in the main JS file. This is a factory function that takes the resolve method as a first parameter.
Here, we can use require in order to tell webpack to split this in a separate chunk, and it will call resolve when the component loads. This is known as call splitting and allows us to load a piece of code at runtime, just like Node.js does.
Let's go back to the app component and use the Async component there. Now, if we run the project, we'll see that the Async component is loaded.
We take a look at the network tab in the developer tools. We see that there are two files loaded, the app.js and indecipherable , which is the common chunk created for the Async component, but they both have loaded at boot time.
That's a bit useless, because what we want is to load that component conditionally. For that, we can create a variable that will work as a flag. Then let's create a button, "Load Async Component." On the click event, we're going to change the variable to true.
The idea is that we load asynchronously that component when that variable is true. For that, we need to use the Vue for directive, so that component will be created when it meets that condition. Let's run this again and see what happens.
As you can see, only the app.js component is loaded, but when we click the button, the assign component chunk is now conditionally loaded from the server. Since the loading is asynchronous, you can defer it as much as you want, for example, if you make an HTTP call to the server.
Let's go ahead and illustrate with a set timeout. We can write the console log just when we request the component and another when it's loaded. Then let's defer this by two seconds. If we click now, we see, "Loading," and after two seconds, it loads the Async component and it shows, "Loaded."
Another way to write this asynchronous function is if you use webpack tool and indecipherable . You can use the import function. That returns a promise which is understood by Vue component factory function as well.
If we try this again, we'll see it's working the same way it was before.