Frontend Patterns

Pattern

Lazy Loading

Defer loading of non-critical resources until they're needed.

Performance Advanced

Lazy Loading

Problem

Initial page load downloads megabytes of JavaScript that users may never use. Critical first-page interactions are delayed because the browser is busy parsing code for admin panels, settings pages, or rarely-accessed features. Time-to-interactive suffers, especially on mobile devices.

Solution

Defer loading of non-critical resources until they’re needed, loading images as they enter the viewport and code when features are accessed. This reduces initial payload and speeds up first render by prioritizing what users see immediately.

Example

This example demonstrates lazy loading an admin panel component so its code is only downloaded when it’s actually rendered, not during the initial page load.

// Lazy load the AdminPanel - code is only fetched when needed
const AdminPanel = lazy(() => import('./AdminPanel'));

function App() {
  return (
    // Suspense shows a fallback while AdminPanel is loading
    <Suspense fallback={<Loading />}>
      {/* AdminPanel code downloads when this component renders */}
      <AdminPanel />
    </Suspense>
  );
}

Benefits

  • Dramatically reduces initial bundle size by loading code only when needed.
  • Speeds up time-to-interactive by prioritizing critical rendering path.
  • Improves perceived performance by making key features available faster.
  • Saves bandwidth for users who never access certain features or routes.

Tradeoffs

  • Introduces loading states and spinners when lazy resources are first accessed.
  • Adds complexity with Suspense boundaries and error handling for failed loads.
  • Can hurt user experience if not combined with preloading or prefetching.
  • Makes it harder to test and debug since code is split across multiple chunks.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.