Why JavaScript costs more than its byte size
| Cost | What happens | Where to measure |
|---|---|---|
| Transfer | JavaScript files are downloaded | Network |
| Parse / compile | Code is prepared for execution | Performance / Lighthouse |
| Execution | Code runs on the main thread | Performance |
| Unused code | Downloaded code is not used in the recorded scenario | Coverage |
JavaScript consumes both network and CPU. After download it must be parsed, compiled and executed, much of it on the main thread. When that thread is busy, user input can be delayed. [1][6][7]
Lighthouse separates transfer-related concerns from parsing, compilation and execution costs, so two similarly compressed bundles can still have very different CPU impact. [6]
MDN's practical guidance is to use as little JavaScript as necessary and defer non-critical code until it is actually needed. [1][2]
Measure before you optimize
Network shows what was downloaded and when, Performance shows main-thread work, Coverage highlights code that was downloaded but not used in the recorded scenario, and Lighthouse surfaces issues such as unused JavaScript and expensive execution. [4][5][6][7]
Coverage does not prove that every red line can be deleted from the entire product. It only reports what was unused during the recorded session, so important user journeys should be tested separately. [4]
Run audits against a production build, disable cache when measuring initial loads and use CPU and network throttling so a fast development machine does not hide problems that appear on weaker devices. [6][7]
What is actually inside a bundle
A bundle commonly contains application code, framework runtime, third-party dependencies, bundler runtime, polyfills and code needed only by other routes or infrequent features.
The first question should not be how to compress everything better, but which modules need to be in the initial JavaScript at all. web.dev describes code splitting as a way to ship only what is needed at startup. [14]
Bundle analysis is especially valuable after adding editors, charting libraries, maps, document parsers or SDKs that are used only by a subset of users.
Tree shaking: remove unused code
Simple code that can benefit from tree shaking
// math.js
export function add(a, b) {
return a + b;
}
export function expensiveDebugHelper() {
console.log("debug helper");
}
// app.js
import { add } from "./math.js";
console.log(add(2, 3));
Tree shaking is dead-code elimination based largely on the static structure of modules. webpack explains that ESM import and export allow bundlers to identify unused exports. [8]
In the example, the application imports only add, so a production bundler may remove the unused expensiveDebugHelper when the module and surrounding code are safe to eliminate. [8]
Do not assume tree shaking is a guarantee. Dynamic patterns, side effects and the way dependencies are published can reduce what static analysis can safely remove.
sideEffects: a small flag with large consequences
Precisely declaring side effects in package.json
{
"name": "my-ui-library",
"sideEffects": [
"**/*.css",
"./src/polyfills.js",
"./src/register-elements.js"
]
}
webpack distinguishes unused exports from entire modules that can be skipped. The sideEffects field in package.json can allow whole unused dependency subtrees to be removed. [8]
sideEffects: false is only safe when importing the module performs no required work beyond exposing exports. CSS imports, polyfills, global registration and initialization code are common side effects that can disappear incorrectly. [8]
Component libraries should mark actual side-effectful files precisely instead of declaring the entire package pure without verification.
Code splitting: do not ship the entire product on the first screen
Code splitting divides an application into chunks that can be loaded in parallel or on demand. webpack documents dynamic import() as a primary split point, while web.dev connects smaller startup payloads with less main-thread work during initialization. [9][14]
Natural split boundaries include routes, optional editors, maps, dashboards, administrative modules and large libraries used only in part of a session.
Do not split every tiny module. Too many chunks can increase request overhead, complicate caching and introduce dependency waterfalls.
Dynamic import() in practice
Load a heavy editor only after interaction
document.querySelector("#open-editor").addEventListener("click", async () => {
const { createEditor } = await import("./editor.js");
const editor = await createEditor();
editor.mount("#editor");
});
import() loads a module asynchronously when execution reaches the expression. MDN describes it as a way to extend the module graph dynamically at runtime. [3]
In the example, the editor is not part of the initial path simply because a button exists. Its chunk is requested only after the user opens the feature.
This is ideal for optional functionality, but not for code required for first render or the first critical interaction.
Dependencies are often more expensive than your own code
A large dependency can add more bytes than the application's own modules. Coverage and bundle analysis help reveal whether users actually execute the code that was shipped. [4][5]
Prefer narrow imports when a package exposes tree-shakable ESM, but do not assume a named import guarantees a tiny result. Side effects and package format still matter. [8]
Compare production output after dependency upgrades because a small packaging or import change can move a surprising amount of code between chunks.
defer, async and truly non-critical code
defer and async serve different purposes
<!-- Preserves document order and executes after HTML parsing -->
<script defer src="/assets/app.js"></script>
<!-- Independent script: executes as soon as it is ready -->
<script async src="https://example-cdn.com/analytics.js"></script>
MDN recommends deferring parsing and execution of non-critical JavaScript. For classic scripts, defer preserves order and runs after HTML parsing, while async runs an independent script as soon as it is ready. [1]
Do not use async when execution order relative to another script matters. For application modules, ESM plus code splitting is often a more structured solution.
Treat analytics, chat widgets and marketing scripts as real performance costs rather than code that somehow sits outside your application.
modulepreload: accelerate only likely-needed modules
Selective modulepreload for a likely-needed module
<link rel="modulepreload" href="/assets/editor.js">
<button id="open-editor">Open editor</button>
<script type="module" src="/assets/main.js"></script>
rel="modulepreload" lets the browser fetch a module early, parse and compile it into the module map. MDN notes that this can reduce dependency-discovery delay. [12]
MDN also warns not to preload everything because aggressive preload can compete with other resources for bandwidth. [12]
A good candidate is a module very likely to be needed shortly after initial render, not a feature most visitors never open.
Minification and compression solve only transfer
Minification reduces source size, while HTTP content compression such as Brotli or gzip reduces transferred bytes. MDN recommends compressing suitable textual resources. [11]
Do not evaluate JavaScript only by its br or gzip size. The browser decompresses the code and still has to parse, compile and execute it. [6][11]
Track transfer size, uncompressed size and CPU time together.
Cache and chunk stability across deployments
Code splitting benefits from caching when unchanged chunks retain stable content-hashed URLs, so changing one feature does not invalidate the whole application.
Vite documents a practical deployment issue: an older page can reference a chunk removed by a new deployment, causing a dynamic-import load error. It recommends avoiding stale HTML references and exposes an error event for this scenario. [10]
A common strategy is short-lived or revalidated HTML combined with long immutable caching for fingerprinted assets.
Bundle size, responsiveness and INP
Less startup JavaScript means less parsing, compilation and execution on the main thread. web.dev links code splitting with freeing the main thread earlier, which can help responsiveness and INP. [14]
Lighthouse separates script evaluation, parsing and compilation from other main-thread categories, helping distinguish network cost from execution cost. [6][7]
If a small bundle performs heavy synchronous work after startup, shrinking the file further will not solve the core issue. Execution must be profiled.
Performance budgets and CI
Illustrative webpack performance budget, choose values from your own measurements
// webpack.config.js
export default {
performance: {
hints: "error",
maxEntrypointSize: 220_000,
maxAssetSize: 220_000
}
};
// The values above are an illustrative budget.
// Set limits from measurements for your own application.
A performance budget turns speed from a one-time audit into an engineering constraint. web.dev recommends budgets that match page types and enforcing them in the build or CI process. [13]
Budgets can cover initial JavaScript, single assets, total transfer, request count or Lighthouse metrics. Values should come from the actual product and devices rather than a universal number. [13]
The example below demonstrates the mechanism. The 220 KB value is intentionally illustrative, not a recommendation for every project.
Current webpack also extends performance with opt-in checks such as duplicate packages, unused modules, async chunk waterfalls and tiny chunks. These can be useful during bundle audits, but some add build-time cost, so enable only the checks that matter. [15]
A practical optimization workflow
Start with a production build and measure initial JavaScript in Network. Then use Coverage on key journeys, Performance for parse/compile/execute work and Lighthouse for unused JS and main-thread diagnostics. [4][5][6][7]
Remove unnecessary dependencies, fix imports and side-effect declarations, verify tree shaking, move heavy optional features behind dynamic import(), and only then refine preload, caching and compression. [3][8][9][11][12]
Finally, enforce a performance budget in CI and repeat the audit after meaningful dependency, routing or architecture changes.
- Measure the production build before changing code.
- Separate initial JavaScript from unused JavaScript.
- Verify tree shaking from the output rather than assuming it works.
- Load optional features through dynamic
import(). - Declare side effects precisely.
- Do not preload everything.
- Monitor network transfer and CPU cost.
- Enforce a budget in CI.
