DEV Community

Alex Sidorenko
Alex Sidorenko

Posted on • Originally published at

How Code Splitting Improves Lighthouse Score

Low Lighthouse performance score

What if there was one single technique that could help increase this score by a lot?

Why having a large JS bundle is bad for performance

Let's say we have a single-page application with six screens. Every screen requires a particular amount of javascript to work. But since it is a single-page application, we load all javascript in one bundle and include it in our index.html.

Six screens - Home, About, Dashboard, Admin, Post, Posts

Now, when a user lands on Home, ideally, we only want to load 100kb of javascript required for this screen. But instead, the browser has to load and parse the entire javascript bundle.

Home screen downloads an entire javascript bundle

Even if the user never accesses "Admin" or "Dashboard" pages, the code for these pages will still have to be loaded. Moreover, if we don't use pre-rendering techniques, the browser will not show the Home screen until the entire bundle is loaded. Therefore bundle loading process blocks the rendering and increases the time for the First Contentful Paint.

How code-splitting helps

What if we could load the code for each screen only when the user lands on this screen. Let's say the user goes from Home to Posts to a single Post. In this case, we don't want to load javascript for Admin, Dashboard and About at all. How do we do that?

Loading screens

This is where code splitting comes in handy.

Code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel.

MDN - Code splitting

Instead of having one large javascript bundle, we split it into smaller chunks and load them on demand.

Splitting code into smaller chunks

When a user lands on Home, the browser loads 100kb home.js and immediately starts rendering the Home screen. If then, the user goes to Posts, the browser loads 200kb posts.js and renders Posts screen, etc. No more unused code, no render-blocking.

How to apply code splitting

There are different code splitting techniques available for various javascript bundlers and frameworks:

Follow me on Twitter

Top comments (0)