Lazy loading

2 snippets across 2 stacks — HTML & CSS, React

Also written as loading lazy

HCHTML & CSS

Lazy Loading Images

HC · Images & Media
syntax
<img src="url" alt="description" loading="lazy">
example
<img src="/gallery/photo-42.jpg" alt="Sunset over the canyon" loading="lazy" width="600" height="400">

Note loading="lazy" defers loading until the image nears the viewport. Do not lazy-load images that are visible on initial load (above the fold) since it slows their appearance. Use loading="eager" (the default) for hero images.

REReact

Suspense & Lazy Loading

RE · Patterns
syntax
const LazyComponent = React.lazy(() => import('./Component'));

<Suspense fallback={<Loading />}>
  <LazyComponent />
</Suspense>
example
import { lazy, Suspense, useState } from 'react';

const AdminPanel = lazy(() => import('./AdminPanel'));
const UserDashboard = lazy(() => import('./UserDashboard'));

function App({ role }) {
  return (
    <Suspense fallback={<div className="spinner">Loading...</div>}>
      {role === 'admin' ? <AdminPanel /> : <UserDashboard />}
    </Suspense>
  );
}

Note React.lazy only works with default exports. For named exports, create an intermediate module that re-exports as default. Suspense can also wrap components that use the use() hook to read promises in React 19.