Frontend System Design · Lesson 67 of 86 · 4 min
Code Splitting, Tree Shaking, Asset Optimization
This is how you explain that your app isn't just fast—it's efficient. Get this right to show you understand the entire delivery pipeline.
Split your code to shrink the initial payload
Your first goal is to send the user the absolute minimum amount of code required to render the initial view. Everything else can wait. This is code splitting.
The most common strategy is route-based splitting. A user on /dashboard doesn't need the code for /settings. You achieve this with dynamic import(), which modern bundlers recognize and use to create separate output files, or "chunks".
Frameworks provide helpers for this. In React, you use React.lazy and Suspense.
// src/App.tsx
import React, { Suspense } from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
// These components will be in separate JS chunks.
const HomePage = React.lazy(() => import('./pages/HomePage'));
const AboutPage = React.lazy(() => import('./pages/AboutPage'));
const App: React.FC = () => {
return (
<Router>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
</Routes>
</Suspense>
</Router>
);
};
export default App;
When the user navigates to /about, the browser makes a network request for the AboutPage chunk. Suspense shows a fallback UI until the chunk is downloaded and ready. You can also split on components, not just routes. A heavy chart library or a rich text editor can be loaded only when the user clicks a button to show it.
The trap: Over-splitting. Creating hundreds of tiny chunks can be slower than a few medium-sized ones. Each new chunk requires another HTTP request. While HTTP/2 mitigates this with multiplexing, there's still overhead. Analyze your bundle with a tool like Webpack Bundle Analyzer and group related, smaller modules into a single chunk if needed.
Shake the tree to eliminate dead code
Tree shaking is dead code elimination. Your bundler statically analyzes your import and export statements and removes any exported code that is never imported by another module.
This works because ES Modules are static. The dependency graph can be determined at build time without running any code. This is a key advantage over CommonJS, where a dynamic require() call can depend on runtime values, making static analysis impossible.
The key detail: For tree shaking to work on your dependencies, the library author must signal that their code is "pure." This is done by setting "sideEffects": false in their package.json. This tells the bundler that importing a module from the package has no side effects (like modifying window or applying global CSS). If it's set incorrectly, the bundler might remove code that was actually necessary.
If a library doesn't set this flag, your bundler will play it safe and include all its code, even if you only import one small function.
Optimize assets, especially images
JavaScript is often not the biggest performance problem. Large, unoptimized images are a common cause of slow page loads and a poor Largest Contentful Paint (LCP) score.
Focus on these three areas for images:
- Format: Use modern formats like WebP or AVIF. They offer better compression than JPEG or PNG. Use the
<picture>element to provide fallbacks for older browsers. - Size: Serve appropriately sized images for the user's viewport. Use the
srcsetandsizesattributes to let the browser choose the best image from a set of options. Don't send a 4000px-wide desktop hero image to a mobile device. - Loading: Defer loading of off-screen images. The easiest way is with the native
loading="lazy"attribute on the<img>tag. The browser will handle the rest.
Fonts are another critical asset. Use the WOFF2 format, subset fonts to include only the characters you need, and use the CSS property font-display: swap to prevent text from being invisible while the font file loads.
How to answer "How would you optimize a slow SPA?"
This question is a test of your systematic approach. Don't just list techniques. Show a process.
- Analyze first. State that you'd begin by profiling. Use Lighthouse to get a baseline and Webpack Bundle Analyzer to see what's actually in your JavaScript bundles. Identify the largest modules and assets.
- Attack the initial bundle. Your first priority is reducing the JavaScript needed for the initial render. Implement route-based code splitting. This is usually the biggest win.
- Verify dead code elimination. Check that tree shaking is working correctly and that you're not importing entire libraries when you only need a single function.
- Optimize assets. After JS, turn to images and fonts. Explain how you'd implement responsive images and lazy loading.
- Mention the basics. Minification and server compression (Brotli/Gzip) are standard practice, but mentioning them shows you haven't forgotten the fundamentals.
This flow demonstrates a structured, data-driven approach to performance optimization, which is exactly what an interviewer wants to hear.
Try it
Take a small multi-page React or Vue project. Refactor it to use React.lazy or defineAsyncComponent for its routes. Open your browser's network tab, disable the cache, and watch the separate JavaScript chunks get loaded as you navigate between pages.
Next: We'll see how bundlers find your files and update them instantly in Module Resolution and Hot Module Replacement.
Lock it in — apply this lesson under interview conditions.