Boost Web Performance with Code Splitting: Practical Guide & Tips
This article explains why reducing initial load resources is crucial for web performance, shows how to measure code utilization with Chrome DevTools, and provides detailed guidance on static and dynamic code splitting, magic comments, and webpack configurations to create faster, smoother front‑end applications.
Introduction
When coaching candidates for front‑end interviews, many struggle to optimize projects; introducing code splitting can significantly improve performance.
Key Web Performance Metrics
Performance hinges on reducing the number and size of resources loaded at initial page load. Recommended targets (considering mobile and international users) are:
Uncompressed JavaScript ≤ 200 KB
Uncompressed CSS ≤ 100 KB
HTTP/1.1 request count ≤ 6
HTTP/2 request count ≤ 20
Code utilization ≥ 90 % (i.e., unused code ≤ 10 %).
While strict, these goals help create high‑performance web apps.
How to Check Code Utilization
Code utilization = (executed code / total imported code) × 100 %.
Use Chrome DevTools (only Chrome supports this) to view coverage:
Open Chrome DevTools.
Press Cmd+Shift+P (or Ctrl+Shift+P).
Type Coverage and select the first result.
Click the reload button in the panel to see JavaScript code utilization.
Improving Code Utilization: Code Splitting
What Is Code Splitting?
Code splitting moves code that is not needed immediately into asynchronously loaded chunks during the build process.
Webpack creates separate files for these chunks and loads them on demand.
How Code Splitting Works
The core idea is asynchronous resource loading . The W3C stage‑3
whatwg/loaderspec defines
import()for dynamic loading.
Although IE does not support
import(), Webpack polyfills it with JSONP, allowing asynchronous loading in all browsers.
Types of Code Splitting
Static Code Splitting
Explicitly declare modules to be loaded asynchronously.
<code>import Listener from './listeners.js';
const getModal = () => import('./src/modal.js');
Listener.on('didSomethingToWarrentModalBeingLoaded', () => {
getModal().then(module => {
const modalTarget = document.getElementById('Modal');
module.initModal(modalTarget);
});
});</code>Each call returns a
Promise.
When to use static splitting:
Large libraries or frameworks that are not needed on initial load.
Temporary resources such as modals, dialogs, tooltips.
Route‑based loading: deliver only the resources required for the current page.
Dynamic Code Splitting
Loads code chunks based on runtime conditions.
<code>const getTheme = (themeName) => import(`./src/themes/${themeName}`);
if (window.feeling.stylish) {
getTheme('stylish').then(module => module.applyTheme());
} else if (window.feeling.trendy) {
getTheme('trendy').then(module => module.applyTheme());
}</code>Webpack creates a context module that contains all possible chunks, so the actual request is still to a static file.
Typical scenarios:
A/B testing – load only the needed UI.
Theming – load a theme based on user preference.
Performance – dynamic splitting can reduce total code size compared to static splitting.
Magic Comments
Webpack magic comments give finer control over generated chunks.
<code>// index.js
import(/* webpackChunkName: "my-chunk-name" */ './footer');</code>Configure
output.chunkFilenamein
webpack.config.jsto name chunks:
<code>{
output: {
filename: "bundle.js",
chunkFilename: "[name].lazy-chunk.js"
}
}</code>Webpack Modes
Beyond
webpackChunkName, you can set
webpackMode(e.g.,
lazyor
lazy-once) to control how async modules are grouped.
Prefetch and Preload
Use
webpackPrefetchto add a
<link rel="prefetch">‑like hint, loading resources during idle time. Enable it only when you are sure the code will be needed later.
<code>import(/* webpackPrefetch: true */ './someModule');</code>Conclusion
We have covered the fundamentals of code splitting, including static and dynamic techniques, magic comments, and webpack configuration tips. Apply these methods to reduce initial load size, improve code utilization, and deliver smoother, faster front‑end experiences.
Taobao Frontend Technology
The frontend landscape is constantly evolving, with rapid innovations across familiar languages. Like us, your understanding of the frontend is continually refreshed. Join us on Taobao, a vibrant, all‑encompassing platform, to uncover limitless potential.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.