If you're familiar with JavaScript applications you may have heard the term code splitting before. So what does it mean?
Definition
According to MDN, "Code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel."
In other words, when you have different chunks of code you can make choices about how you load them. When you only have one big one, your hands are tied.
But what does code splitting get you? And why is it necessary?
Performance
When your application is bundled up for use, it isn't just your application code that's included. The bundle also comes with all the third-party libraries your code uses. That can make for a pretty big bundle size! And as the size of this bundle increases, loading it can become costly.
Suppose all of that code had to be downloaded every time a user loaded a page. It could take a considerable amount of time until the page was usable. This is not a great experience for users.
The solution
Code splitting allows you to break up the monolithic bundle into various smaller bundles. You can then load the bundles in parallel or implement lazy loading, delaying download of certain code until a user needs it.
Tools
The most common tools for implementing code splitting are Webpack and Browserify. However, you may be implementing code splitting behavior without even realizing it.
Async
You're likely used to code at the top of your file that looks like this.
import MyScript from './my-script'
This includes my-script
in your main application bundle.
However, there is another way. Suppose you only needed that script to run in a certain scenario.
function myFunction() {
if (condition) {
import(`./my-script`).then(() => {
// do something here
})
}
}
If you've read my Node or Webpack post you may recall that Webpack often has implementations of functions you think you're familiar with. In this case, the code above is using Webpack's import function, not the browser or Node.js supported dynamic import. It loads the script asyncronously, so that it doesn't hold up the rest of the code, and returns a Promise.
By doing this, the code inside my-script
becomes part of a different bundle. The snippet above is performing code splitting!
Is that it?
There is a lot to talk about here. Bundling and performance are vast topics! But this is a nice primer.