What is Code Splitting?

JavaScript Performance ImportantUberNetflix

Code Splitting

It's a fundamental technique in modern frontend development that can significantly improve your application's performance.

In JavaScript, traditional bundling works by combining all your code into a single large file. While this ensures everything is available, it means users have to download the entire application before they can use any part of it which is not efficient. This is where code splitting comes in.

Here's a practical example to illustrate code splitting:

// Without code splitting - everything loads at once
import HomeComponent from './Home';
import ProfileComponent from './Profile';
import SettingsComponent from './Settings';

// With code splitting - components load on demand
const HomeComponent = React.lazy(() => import('./Home'));
const ProfileComponent = React.lazy(() =>
import('./Profile')
);
const SettingsComponent = React.lazy(() =>
import('./Settings')
);

Code splitting offers several key benefits:

  • First, it reduces the initial bundle size. Instead of loading your entire application upfront, users download only what they need for the current page or feature. This leads to faster initial page loads - imagine if Facebook made you download all its features before you could see your news feed!
  • Second, it enables more efficient caching. When you update one part of your application, users only need to download the changed chunks, not the entire application again.
  • Modern JavaScript frameworks provide different ways to implement code splitting:
// Route-based code splitting in React
import {
BrowserRouter,
Route,
Switch,
} from 'react-router-dom';
import React, { Suspense } from 'react';

// Each route becomes a separate chunk
const Dashboard = React.lazy(() =>
import('./routes/Dashboard')
);
const Settings = React.lazy(() =>
import('./routes/Settings')
);

function App() {
return (
<BrowserRouter>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route path="/dashboard" component={Dashboard} />
<Route path="/settings" component={Settings} />
</Switch>
</Suspense>
</BrowserRouter>
);
}

You can also use code splitting for specific features or components:

// Component-based code splitting
function MyComponent() {
const [showChart, setShowChart] = useState(false);

// Chart component will only be loaded when button is clicked
const Chart = React.lazy(() => import('./Chart'));

return (
<div>
<button onClick={() => setShowChart(true)}>
Show Chart
</button>
{showChart && (
<Suspense fallback={<div>Loading chart...</div>}>
<Chart />
</Suspense>
)}
</div>
);
}

The webpack bundler (which many frontend build tools use under the hood) handles the actual splitting of your code into smaller chunks. It analyzes your import statements and creates separate files that are loaded asynchronously when needed.

00:00

Table of Contents