Home / Blog / How to Prefetch a Vue.js Component
How to Prefetch a Vue.js Component

How to Prefetch a Vue.js Component

Daniel Kelly
Daniel Kelly
Updated: January 2nd 2025
This entry is part 2 of 2 in the series The Ultimate Guide to Vue Performance

Vue.js offers powerful ways to optimize application performance through component preloading. In this article, we'll explore how to implement component prefetching to enhance your application's user experience and loading times.

Understanding Component Preloading in Vue

Before diving into the implementation, let's understand what component preloading means and why it's important. In a typical Vue.js application, components are loaded when they're needed - a pattern known as lazy loading or code splitting. While this approach reduces the initial bundle size, it can lead to slight delays when components are first accessed.

Component preloading solves this problem by initiating the download of components before they're actually needed, typically when a user shows intent to interact with them (like hovering over a button).

The modal overlay component is preloaded on hover of the button so that itā€™s 100% ready to show as soon as the user clicks

Common Use Cases for Preloading

Some common use cases for preloading Vue components include:

The Evolution of Preloading in Vue Applications

Historically, when building Vue applications with Webpack, developers could leverage Webpack's built-in preloading capabilities using magic comments. For example:

// Webpack approach
import(/* webpackPrefetch: true */ './MyComponent.vue')

However, with the rise of Vite as the preferred build tool for Vue applications, this approach is no longer available out of the box. Vite's architecture, while providing faster development and build times, doesn't include native support for these Webpack-specific features. This has led to the need for alternative approaches to component preloading, which we'll explore in this article.

How to Implement Component Preloading in Vue and Vite

Let's walk through a practical example of implementing component preloading in Vue.js with Vite. Hereā€™s the full code. Next weā€™ll break it down step by step.

<script setup lang="ts">
import { ref, defineAsyncComponent } from 'vue';

// Define our async component imports
const loadComponent = () => import('@/components/CodeSplitExampleComponent.vue')
const loadRoute = () => import('@/views/HomeView.vue')

// Create the async component
const CodeSplitExampleComponent = defineAsyncComponent(loadComponent)

// Control component visibility
const show = ref(false);
</script>

<template>

    <!-- Preload on hover, show on click -->
    <button
        @mouseenter="loadComponent"
        class="btn mb-3"
        @click="show = !show"
    >
        Toggle Code Splitting Example
    </button>

    <!-- Conditionally render the component -->
    <CodeSplitExampleComponent v-if="show" />

    <br>

    <!-- It works for preloading pages too! -->
    <router-link
        @mouseenter="loadRoute"
        to="/"
        class="link"
    >
        Go Home
    </router-link>
</template>

How the Preloading System Works

  1. Component Definition: We use defineAsyncComponent to create a component that will be loaded asynchronously. This is the foundation of code splitting in Vue.
  2. Import Functions: We define separate import functions (loadComponent and loadRoute) that return dynamic imports. Since we can't use Webpack's magic comments in Vite, these functions serve as our preloading mechanism.
  3. Trigger Events: We implement preloading through the @mouseenter event. When a user hovers over an element, the corresponding import function is triggered, initiating the download.
  4. Conditional Rendering: The actual component is only rendered when needed (controlled by the show ref in our example), but the code is already downloaded thanks to the preloading.

Some Best Practices for Component Preloading

When implementing component preloading in your Vue.js application, consider these important practices:

Choose the Right Trigger Events

The mouseenter event is commonly used for preloading, but you might want to consider other triggers based on your specific use case:

  • On page load for critical components
  • On scroll when approaching certain elements
  • On user interaction with related features

The below code shows how you can preload the component in a non-blocking fashion when the page loads.

<!--PageComponent.vue-->
<script setup lang="ts">
// rest is the same as above

// call load component directly in script setup
// but don't `await` for it to finish!
loadComponent() 
</script>

<template>
        <!-- Don't add the mouse enter event this time)-->
    <button
        @mouseenter="loadComponent"āŒ
        ...
     >...</button>
        <!-- Rest is the same as above -->
</template>

Balance Preloading and Performance

While preloading can improve perceived performance, preloading too many components can have the opposite effect. Consider these factors:

  • Component size and complexity
  • User bandwidth and device capabilities
  • Likelihood of the component being needed

The Waterfall Problem

Another issue to consider is the "waterfall effect". This is a common performance issue that can negate the benefits of preloading. When preloading components, you might encounter a situation where loading one component triggers a cascade of dependent resource loads. The flow looks like this:

  1. The Initial component loads
  2. Dependencies are discovered and load
  3. Sub-dependencies are discovered and load
  4. and on and an further down the tree

This creates a waterfall of network requests, each waiting for the previous one to complete before starting.

// Problematic approach that can cause waterfalls
const ComponentA = defineAsyncComponent(() => import('./ComponentA.vue'))
// ComponentA loads, then discovers it needs to load another component, etc

The moral of the story, is that you should be thoughtful when it comes to code splitting components and how/if you preload them.

Error Handling with Async Components

For even more control over you async components pass an object to defineAsynComponent with an error component to display on load fail. Plus, customize a variety of other options as well.

const Component = defineAsyncComponent({
  loader: () => import('./MyComponent.vue'),
  loadingComponent: LoadingSpinner,
  errorComponent: ErrorDisplay,
  delay: 200,
  timeout: 3000
})

Performance Impact and Monitoring

After all your efforts to speed up your application with component code splitting and preloading itā€™s important to measure which approaches are effective and which arenā€™t. Follow up your optimization efforts by:

  1. Monitoring loading times before and after implementing preloading
  2. Using browser developer tools to observe network requests
  3. Tracking user interaction patterns to optimize preloading triggers
  4. Considering implementing performance metrics tracking

Conclusion

Component preloading in Vue.js is a powerful optimization technique that can significantly improve your application's user experience. While the approach has evolved from Webpack's magic comments to more manual methods in Vite, the benefits of preloading remain substantial. By understanding when and how to implement preloading, you can create more responsive applications without sacrificing initial load performance.

Remember that preloading is just one tool in your optimization toolkit. Combine it with other performance optimization techniques like proper code splitting, caching strategies, and efficient component design for the best results. You can learn how to implement these performance techniques and more in our course The Ultimate Guide to Vue Performance.

Related Courses

Start learning Vue.js for free

Daniel Kelly
Daniel Kelly
Daniel is the lead instructor at Vue School and enjoys helping other developers reach their full potential. He has 10+ years of developer experience using technologies including Vue.js, Nuxt.js, and Laravel.

Comments

Latest Vue School Articles

The Ultimate Guide to Vue Performance &#8211; A Comprehensive Course for Building Lightning Fast Applications

The Ultimate Guide to Vue Performance – A Comprehensive Course for Building Lightning Fast Applications

Learn essential Vue.js performance optimization techniques in this comprehensive course. Master code splitting, component optimization, efficient data fetching, and debugging tools to build lightning-fast applications.
Daniel Kelly
Daniel Kelly
How To Scrape Amazon with Playwright and Bright Data

How To Scrape Amazon with Playwright and Bright Data

Learn how to build a reliable Amazon web scraper using Playwright and Bright Data. This guide covers setup, product data extraction, pagination handling, and best practices to avoid blocks while scraping Amazon's search results.
Daniel Kelly
Daniel Kelly

Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.

More than 200.000 users have already joined us. You are welcome too!

Follow us on Social

Ā© All rights reserved. Made with ā¤ļø by BitterBrains, Inc.