An overview of lazy loading
Lazy loading, like most concepts we have been discussing in this series, is not peculiar to react.
Lazy loading is a design pattern commonly used in computer programming and in web design and development to defer the initialization of an object until the point at which it is needed.
This can contribute to the efficiency of the program's operation if properly and appropriately used. It is also known as asynchronous loading, code splitting, and data fetching. The opposite of this operation is eager loading.
Lazy loading is very ideal in use cases where network content is accessed and initialization should be kept at a minimum such as with web pages. For example, deferring the loading of images on a web page until they are needed can make the initial display of the web page faster.
Lazy loading as a web standard
Since 2020, major web browsers now natively handle lazy loading by default. Lazy loading is now incorporated into a webpage by simply using HTML attributes.
Images
Images have the loading attribute on an <img>
element (or the loading attribute on an <iframe>
) that can be used to instruct the browser to defer the loading of images/iframes that are off-screen until the user scrolls down to them.
The loading attributes support two values - lazy and eager.
Setting the value to lazy will fetch the resource only when it is required. Setting the video to eager which is the default will load the resource immediately.
<!-- These resources will be loaded immediately -->
<img src="header_image.jpg">
<img src="header_image2.jpg" loading="eager">
<!-- These resources will be lazy-loaded -->
<img src="article_image.jpg" alt="..." loading="lazy">
<iframe src="video-player.html" title="..." loading="lazy"></iframe>
JavaScript
Any script tag with type="module" is treated as a JavaScript module and is deferred by default.
Fonts
By default, font requests are delayed until the render tree is constructed, which can result in delayed text rendering. This is not advised, but the default behaviour can be overridden with <link rel="preload">
to preload font resources
CSS
By default, CSS is treated as a render-blocking resource, so the browser won't render any processed content until the CSSOM is constructed.
Lazy Loading in react
We have seen that by default, the web supports lazy loading. Why and how can it be applied in react applications?
Why?
React bundles the complete code and deploys all of it at the same time. Now, this is not a bad idea, since React SPAs (Single page applications) are small and do not affect the performance. But what if we had a larger application with different user roles - the customer portal, the admin portal, etc? In this case, it does not make much sense to load the entire application.
A customer login, will not have access to admin-specific features, so loading it is a waste of memory and can lead to slow loading of the website.
What then is the solution?
You already guessed it, lazy loading
How?
React 16.6+ now supports react.lazy() and react.suspense() inbuilt to support lazy loading.
React.lazy()
React.lazy() lets you define a component that is loaded dynamically. This helps reduce the bundle size to delay loading components that aren’t used during the initial render.
// regular import ❌
const SomeComponent = import('./SomeComponent'));
// component loaded dynamically ✅
const SomeComponent = React.lazy(() => import('./SomeComponent'));
React.suspense()
React.Suspense lets you specify what should be rendered in case some components in the tree below it are not yet ready to render.
In the code below, someComponent has been lazily imported and rendered in MyComponent, and in the case that it is not yet ready to be rendered, the fallback is Spinner and it will be displayed.
const SomeComponent = React.lazy(() => import('./SomeComponent'));
function MyComponent() {
return (
// Displays <Spinner> until SomeComponent loads
<React.Suspense fallback={<Spinner />}>
<div>
<SomeComponent />
</div>
</React.Suspense>
);
}
Why should you care
- Reduces initial load time – Lazy loading of a webpage reduces page weight, allowing for a quicker page load time.
- Bandwidth conservation – Lazy loading conserves bandwidth by delivering content to users only if it’s requested.
- System resource conservation – Lazy loading conserves both server and client resources because only some of the images, JavaScript and other code actually need to be rendered or executed.
- Improved SEO: Page load speed is important for SEO because it is one of the key determining factors for Google's algorithm. Slow sites turn visitors away. Fast sites provide good user experiences for your visitors, and Google will rank those sites higher than slow-loading ones
Lazy loading impacts how search engines crawl your site. If your page doesn't immediately load, search engines can't crawl the entire page. This means that your content will be ignored or misinterpreted.
🍵 Happy coding