How code splitting increases performance
When your application grows and your number of users increases, optimizing for performance becomes more and more important.
I previously wrote an overview of things you can do to increase the performance of your application when you are using webpack. One of those things is code splitting.
What is code splitting?
But how can that increase performance?
So if you have one big bundle and if you just change one single line of code then your whole bundle needs to be reloaded.
Here is where code splitting comes into play.
If you instead split your bundle up to many smaller bundles with code splitting, and you change one of them, the others don’t need to be reloaded because they haven’t changed.
Less full reloads of resources makes the site quicker!
You can also configure your split bundles to be loaded asynchronously. That means that only the parts of your application that are in use will be loaded. So for example if a user clicks a button that will open a modal, the code for the modal will be loaded right before the modal is displayed for the first time - not on page load.
But wait a minute, isn’t many files slower?
If you have been coding frontend for a few years you have learned that having many resources on your site it’s slow. The reason is that the overhead of each HTTP connection is a big performance cost, especially on mobile.
But things have changed the last couple of years.
In HTTP2, which is the latest major version of HTTP, the headers are compressed which creates little to no overhead for each connection. Most modern web servers support HTTP2.
So these days it is no longer slower to have many resources on your site!
What can you split?
A webpack bundle consists of one or many of the following:
- The production code you have written
- Your dependencies
All of these can be split up into it’s own bundles.
You can also split your production code into many bundles.
Action challenge: What can you split in your production application?
Now think about your own production application. Would it make sense to use code splitting to increase performance? How?
Here are som examples to get you started:
- Do you have big SPA with only one bundle? Maybe you should consider async loading.
- Are you using CSS in JS? Maybe you should consider extracting that CSS to a separate bundle (Or a separate CSS file).
- Roughly how often do you change dependencies in your app compared to how often you change the production code? Would it make sense to split your dependencies to a separate bundle?
Think about your application and what you can split to increase performance for your users!
Next step is to implement the code splitting. I will cover the implementation of code splitting in future articles. Subscribe below to be sure that you don’t miss it!