100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
JavaScript

Lazy Loading and Code Splitting

Covers how to split a Vue application into smaller chunks using dynamic imports for routes and components, reducing initial bundle size and improving load performance.

Performance & ProductionIntermediate9 min readJul 9, 2026
Analogies

Lazy Loading and Code Splitting

As a Vue application grows, bundling every component, route, and library into a single JavaScript file means users pay the download and parse cost for the entire application before they can interact with even the first screen. Code splitting solves this by breaking the bundle into smaller chunks that are loaded on demand, typically driven by dynamic import() calls that the build tool (Vite or webpack) automatically recognizes as split points. Lazy loading is the runtime behavior that results: instead of eagerly importing a component or route module at startup, the browser fetches it only when it is actually needed, such as when the user navigates to a specific route.

🏏

Cricket analogy: Packing every player's full career stats booklet into one heavy program before a fan can even see today's scorecard is wasteful — code splitting is like handing out only today's team sheet first, fetching Sachin Tendulkar's full career archive only if the fan taps his name.

Route-level code splitting with Vue Router

The most impactful place to apply code splitting in a typical Vue app is at the route level, since users rarely visit every route in a single session. Vue Router supports this natively: instead of importing a route's component eagerly at the top of the router configuration file, you pass a function that returns a dynamic import(). The router then only fetches that chunk when the user actually navigates to the matching path, keeping the initial bundle limited to the shell of the application plus whatever route is loaded first.

🏏

Cricket analogy: A cricket stats app doesn't preload the "Bowling Records" page until a fan actually taps that tab — Vue Router's dynamic import per route is like only printing that section of the scorecard booklet when someone asks to see it.

javascript
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'home',
    // Eager: loaded immediately, part of the main bundle
    component: () => import('@/views/HomeView.vue'),
  },
  {
    path: '/reports/:reportId',
    name: 'report-detail',
    // Lazy: its own chunk, fetched only when this route is visited
    component: () => import('@/views/ReportDetailView.vue'),
  },
  {
    path: '/admin',
    name: 'admin',
    component: () => import('@/views/AdminDashboardView.vue'),
  },
]

export const router = createRouter({
  history: createWebHistory(),
  routes,
})

Lazy-loading individual components

Beyond routes, Vue's defineAsyncComponent lets you lazily load any component, which is especially useful for large, rarely-used UI such as modals, rich text editors, charting libraries, or admin-only widgets that would otherwise inflate the bundle for every visitor even if most never open them. defineAsyncComponent also accepts an options object supporting loading and error components, plus a delay and timeout, so you can show a spinner only if the fetch takes noticeably long rather than flashing it on every fast load.

🏏

Cricket analogy: A DRS (Decision Review System) replay overlay only loads its heavy video-analysis code when an umpire actually calls for a review, not on every ball — like defineAsyncComponent lazily loading a rarely-used modal, with a short delay before showing "loading review" so it doesn't flash on quick reviews.

vue
<script setup>
import { defineAsyncComponent } from 'vue'

const ChartWidget = defineAsyncComponent({
  loader: () => import('@/components/ChartWidget.vue'),
  loadingComponent: () => import('@/components/SpinnerIcon.vue'),
  delay: 200,
  timeout: 8000,
})
</script>

<template>
  <section>
    <h2>Monthly Revenue</h2>
    <Suspense>
      <ChartWidget />
      <template #fallback>
        <p>Loading chart</p>
      </template>
    </Suspense>
  </section>
</template>

Under the hood, both () => import(...) in a route definition and defineAsyncComponent rely on the same ES module dynamic import syntax. The build tool statically detects these calls and generates a separate chunk file for each unique import target, then wires up the runtime fetch — no manual bundler configuration is required in a standard Vite-based Vue project.

Over-splitting can backfire: turning every small component into its own chunk multiplies the number of network requests and can make the app feel slower due to request overhead and waterfalls, especially on high-latency connections. Reserve lazy loading for genuinely large, rarely-needed, or route-boundary code, and let the bundler's default chunking handle the rest. It's also worth combining lazy loading with prefetching where it makes sense — for example, prefetching the likely next route's chunk on link hover so the perceived load time on click is minimal, which Vite supports via automatically generated modulepreload hints for statically analyzable dynamic imports.

  • Code splitting breaks a Vue app into smaller chunks loaded on demand instead of one large upfront bundle.
  • Vue Router supports lazy route components natively via component: () => import('...').
  • defineAsyncComponent lazily loads individual components, useful for large or rarely-used UI like modals and charts.
  • Async components can specify loading and error components, plus delay and timeout options.
  • Over-splitting into too many tiny chunks can hurt performance due to request overhead — reserve it for genuinely large or route-level code.
  • Prefetching likely-needed chunks (e.g., on link hover) can hide the latency cost of lazy loading.

Practice what you learned

Was this page helpful?

Topics covered

#JavaScript#VueJsStudyNotes#WebDevelopment#LazyLoadingAndCodeSplitting#Lazy#Loading#Code#Splitting#StudyNotes#SkillVeris