CodePark/ questions / JavaScript bundle size
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › JavaScript bundle size

The PDF library is loaded on demand. The user clicks the button three times. How many times does "pdf module runs" print, and how many times is the chunk downloaded?

// pdf.js
console.log("pdf module runs");
export function exportPdf() { /* ... */ }

// app.js
button.addEventListener("click", async () => {
  const { exportPdf } = await import("./pdf.js");
  exportPdf();
});
It prints once and downloads once, on the first click

The first import() downloads the chunk and runs the module once. Later calls get the same module from the module map, so nothing runs or downloads again.

"It prints three times and downloads once" is the tempting wrong answer. A module's top-level code runs only once per page, however often you import it. The cost is a delay on the first click. You can hide it by starting the import earlier, for example on hover or when the browser is idle.