Webpack and Vue together make it possible to split your bundle in chunks and lazy load only the actually needed chunks. Usually one chunk is one view, one component, or one of any encapsulated bunch of only optionally shown piece of content, a software component. This, of course, means that the client makes fewer requests to the server, transfers fewer kb over the network, and parses, compiles and evals fewer lines of JavaScript etc. Huge win.
I’ve been using this pattern with Nyssetutka.fi for quite a some time. The client loads more or less the minimum needed JS payload in order to get the UI going as fast as possible and then conditionally more if the user navigates to some specific views. This isn’t the complete truth and there are a couple of things I could do to make the initial payload even smaller but the gist of it is that not everything is loaded at once in the beginning.
The other day I 15 minutes of hard time googling around along the lines of the title of this blog posting. How would one lazy load the root component of a Vue application? Couldn’t find the answer anywhere so here it is:
const rootComp = () => import('./components/rootComp.vue'); new Vue({ el: "#app-container", render: h => h(rootComp) })
Now that I know the answer… it’s completely clear and logical that this is the way to do it. It’s the completely same syntax you would use for any other component lazy loading but here you just use it for the root component. But even if it’s kinda implicit that this is the way, the official Vue documentation nor any of the Vue lazy loading blog postings out there mention it. So here it is if someone else is looking for the info.
When could this be useful? The answer is not so clear if you compare it to lazy loading just normal components. They’re normal components not needed at the initialization of the app, right, but why would you lazy load the root, eh? If your app has multiple Vue instances and you don’t need them all either at the beginning or at all. In my case the app implements a notification popup telling about new updates and improvements to the site. The popup was easy to implement as a completely separate component used only by a separate Vue instance sharing the same Vuex store with the main app. So this was the way to do it – the popup itself is shown only to a small number of visitors, conditionally, and only once.