Reader small image

You're reading from  JavaScript Design Patterns

Product typeBook
Published inMar 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781804612279
Edition1st Edition
Languages
Right arrow
Author (1)
Hugo Di Francesco
Hugo Di Francesco
author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

Right arrow

Maximizing Performance – Lazy Loading and Code Splitting

In order to maximize the performance of a JavaScript application, reducing the amount of unused JavaScript being loaded and interpreted is key. The techniques that can be brought to bear on this problem are called lazy loading and code splitting. Lazy loading and code splitting allows parts of the JavaScript to be loaded on demand as required. This is in contrast to being downloaded on page load and can greatly reduce the amount of unused JavaScript being loaded and interpreted.

We’ll cover the following topics in this chapter:

  • The dynamic import syntax and how Vite can automatically code-split based on the syntax
  • Route-based code splitting with Next.js and how to read the Bundle Analyzer reports
  • How to use next/dynamic and react-intersection-observer to load JavaScript and React components on different user interactions

By the end of this chapter, you’ll be able to identify and...

Technical requirements

You can find the code files for this chapter on GitHub at https://github.com/PacktPublishing/Javascript-Design-Patterns

Dynamic imports and code splitting with Vite

Dynamic imports in JavaScript refer to the usage of the import() syntax to import a module. Unlike the import Something from './my-module.js' declarative syntax, import() is more akin to a function that returns a promise. For example, we could rewrite the original import as const Something = await import('./my-module.js').

The “dynamic” part of the import is that it doesn’t have to be done at module evaluation time; it’s done as part of the execution of the code. This is useful when paired with code splitting – which we’ll define now – since it means that we can avoid loading and evaluating some JavaScript code until it’s needed.

Code splitting is a technique whereby code is built into multiple files (also known as “chunks” or “bundles”) instead of a single file. Code splitting is useful to avoid loading all the code up front. Instead...

Route-based code splitting and bundling

Let’s begin by defining a route in a general web application context and then in a Next.js context.

In a web application, a route comes from the router concept; in simple terms, it’s an entry in the router. An entry in the router mechanism can take multiple shapes – for example, in an nginx/Apache/Caddy web server setup, we can have a path to file forwarding or a wildcard forwarding approach. In backend MVC frameworks such as Ruby on Rails, Laravel (PHP), and Django (Python), a route associates a request path to the specific code to be run. The request path to code to be run concept also applies to Node.js backend applications using libraries such as Express, Koa, Fastify, and Adonis.js.

Let’s now see how the route concept is used in the Next.js filesystem router.

A minimal Next.js project as initialized with create-next-app is laid out as follows. Each file in the pages directory corresponds to a route. For...

Loading JavaScript on element visibility and interaction

In this section, we’ll look at four different scenarios where dynamic or lazy loading of React components and JavaScript modules can be applied in the context of a Next.js application.

The first instance will be whether the component is in the component tree or not – in other words, whether it’s considered to be rendered or not. Next, we’ll look at dynamic imports based on user interaction. We’ll also cover how to handle an interaction that potentially requires a dynamic import of a JavaScript resource. Finally, we’ll show how to dynamically load a React component when an element is visible in the viewport.

Next.js provides a dynamic utility (see the documentation at https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading) that allows us to lazily and dynamically load a React component.

In our case, we have a components/Hello.jsx component with a Hello...

Summary

In this chapter, we’ve covered various approaches for maximizing the performance of your JavaScript, React, and Next.js applications with lazy loading approaches and code splitting.

First, we showcased how to use the dynamic import syntax in a Vite-powered setup to cause code splitting and illustrated it by importing additional code only when it’s required (during an interaction handler).

Next, we saw how Next.js provides out-of-the-box route-based code splitting while also ensuring modules shared across pages don’t get loaded or output more than once. We also delved into how to validate this using the Next.js Bundle Analyzer plugin.

Finally, we covered how to implement different lazy loading scenarios in Next.js: on presence in the component tree, on change caused by user interaction, importing a JavaScript module during an event handler, and lazy loading on an element entering the viewport.

We now know how to leverage lazy loading and code...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
JavaScript Design Patterns
Published in: Mar 2024Publisher: PacktISBN-13: 9781804612279
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco