BattlefyBlogHistoryOpen menu
Close menuHistory

Demystifying code splitting

Ronald ChenDecember 6th 2021

In our last blog post on Demystifying Webpack, we touched on a few optimization techniques to reduce the bundle size. This week, we will use a sample Webpack project to demonstrate one of them: code splitting in the form of common chunk extraction.

Baseline

The sample Webpack project has two entry points, the home page and my team page.

Webpack config of entry and output,

entry: {  
  main: './index.js',  
  'my-team': './my-team/index.js'  
}  
  
output: {  
  filename: 'bundle.[name].[contenthash].js'  
}

Code splitting

Since the two pages are in the same npm project, it means they will share dependencies. Given this project uses React, it is embedded in both bundles. We are making our users suffer, having them download React redundantly for each page they visit.

Ideally our users would only download React once. Either the first time they visited or the home page or my team page. This is where the Webpack split chunks plugin comes into play.

The split chunks plugin can be used in many ways, but we’ll use it in its most simple form. Just chunk everything. The plugin will figure out the common dependencies and create common bundle of them.

Webpack config to chunk everything,

optimization: {  
  splitChunks: {  
    chunks: 'all'  
  }  
}

We compare the code split bundle size against the baseline and discover we’ve extracted 400 KB common npm dependencies into a shared bundle! Note these are the gzipped sizes. You do have compression turned on for your CDN right?

Another neat thing with code splitting into more bundles is the browser can download them in parallel. Consider how the browser works in these two scenarios,

Baseline

  1. User visits home page
  2. Download 468 KB
  3. User visits my team page
  4. Download 512 KB

Code split

  1. User visits home page
  2. Download 60 KB, 16 KB, 400 KB in parallel, total time = max(60, 16, 400) = 400
  3. User visits my team page
  4. Download 44 KB, 72 KB, 400 KB (cached) in parallel, total time = max(44, 72, 0) = 72

Thus, the bundle size doesn’t even tell the full story. From the user’s perspective, code-splitting results in (400 + 72) / (980) = 48% of the load time!

This assumes the user’s internet has the capacity to download all the bundles in parallel. There are also limits to how many resources browsers will download in parallel per domain. Real-world constraints need to be tested.

If you want to learn more about Webpack or how to optimize it, you’re in luck. Battlefy is hiring.

Demystifying Webpack
November 29th 2021

2022

Powered by
BATTLEFY