Skip to content

Lazy Loading

In web development, lazy loading is a combination of multiple techniques to load resources (non-critical) only when needed. By deferring loading on non-critical elements, the main elements can be rendered faster.

Here are some techniques

loading="lazy"

For <img> and <iframe> HTML attributes adding loading="lazy" will instruct the browser to defer loading the content until the user scrolls near the element.

html
<img loading="lazy" src="image.png" alt="..." />

React.lazy

Calling React.lazy on a component will defer the loading of the component's code until it's rendered for the first time. This is especially useful to reduce the initial JavaScript load size. For example if you have multiple pages, you may want to lazy load the pages so the code only loads if the user clicks on that page.

For example say the app has "Home Page" and "Account Page". Normally the import statement may look like:

js
import AccountPage from './AccountPage';

To defer the loading we wrap the import with lazy:

js
import { lazy } from 'react';
const AccountPage = lazy(() => import('./AccountPage'))

And the final step here would be to wrap the AccountPage with Suspense so that we can render a fallback while the code is loading:

js
<Suspense fallback={<Loading />}> 
	<AccountPage />
</Suspense>