Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

JavaScript performance: reduce bundle size and speed up your application

A large JavaScript bundle costs more than transfer bytes. The browser must download, decompress, parse, compile and execute it, often on the same main thread that also handles user interaction. Good frontend optimization is therefore not about blindly shrinking one file. It is about shipping the right code at the right time and preventing regressions as the application evolves.

Published Written by Reading time 24 min read
On this page Contents: quick navigation between sections

Why JavaScript costs more than its byte size

CostWhat happensWhere to measure
TransferJavaScript files are downloadedNetwork
Parse / compileCode is prepared for executionPerformance / Lighthouse
ExecutionCode runs on the main threadPerformance
Unused codeDownloaded code is not used in the recorded scenarioCoverage

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.

A strong JavaScript performance process follows a clear order: measure, remove unnecessary code, split what remains by when it is needed, control dependency cost, compress transfer, prioritize loading carefully and enforce a budget in CI. Tree shaking, lazy loading and code splitting are not goals by themselves. They are tools for reducing the amount of work required before the first useful interaction and for keeping main-thread pressure under control on real devices.

Tools for this topic

JavaScript Performance Bundle Size Tree Shaking Code Splitting Dynamic Import Frontend Performance Web Performance Lighthouse Chrome DevTools ES Modules Main Thread Performance Budget Webpack Vite

Frequently asked questions

Does a smaller bundle always mean a faster application?

It usually helps, but it may not fix the real bottleneck. A small bundle can still do expensive main-thread work, so parse, compile and execution time must also be measured. [6][7]

Does tree shaking happen automatically?

Modern bundlers support it, but effectiveness depends on module format, side effects and production configuration. [8]

Should I always set sideEffects: false?

No. Incorrect use can remove CSS, polyfills or initialization code. [8]

When should I use dynamic import()?

When code is needed only after entering a route or using an optional feature, not for the critical startup path. [3][9]

Can code splitting improve INP?

It can help by reducing startup parsing, compilation and execution work. Final INP also depends on later handlers and main-thread tasks. [14]

Is Brotli enough to optimize JavaScript?

No. Brotli reduces transfer, but decompressed JavaScript still needs to be parsed and executed. [6][11]

What does Coverage tell me?

It shows used and unused JavaScript and CSS bytes for the recorded session. It does not automatically prove that unused code is safe to delete globally. [4]

Should modulepreload include every chunk?

No. MDN warns that excessive preloading can compete for bandwidth with more important resources. [12]

Are async and defer interchangeable?

No. defer preserves order and runs after HTML parsing, while async executes an independent script when ready. [1]

Is there one universal performance budget?

No. The budget should match page type, target devices and product goals, then be enforced in CI. [13]

Why can dynamic imports fail after deployment?

An old document can reference a chunk removed by the new deployment. Vite documents this scenario and recommends appropriate HTML caching and load-error handling. [10]

Where should bundle optimization start?

With a production build, Network, Coverage and Performance. Remove unnecessary code first, split what remains, then tune preload and compression. [4][5][6][9]

Sources and references

  1. MDN, JavaScript performance optimization↩1↩2↩3↩4
  2. MDN, Web Performance best practices↩
  3. MDN, Dynamic import()↩1↩2↩3
  4. Chrome DevTools, Coverage: Find unused JavaScript and CSS↩1↩2↩3↩4↩5↩6
  5. Lighthouse, Remove unused JavaScript↩1↩2↩3↩4
  6. Lighthouse, Reduce JavaScript execution time↩1↩2↩3↩4↩5↩6↩7↩8↩9↩10
  7. Lighthouse, Minimize main thread work↩1↩2↩3↩4↩5↩6
  8. webpack, Tree Shaking↩1↩2↩3↩4↩5↩6↩7↩8
  9. webpack, Code Splitting↩1↩2↩3↩4
  10. Vite, Building for Production↩1↩2
  11. MDN, Compression in HTTP↩1↩2↩3↩4
  12. MDN, rel=modulepreload↩1↩2↩3↩4
  13. web.dev, Performance budgets 101↩1↩2↩3
  14. web.dev, Reduce JavaScript payloads with code splitting↩1↩2↩3↩4
  15. webpack, Performance configuration↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning