JavaScript · Performance · Mid-Level · Best Practice
How does code splitting and dynamic `import()` improve performance?
Short Interview Answer
Load only the JS needed for the current route/feature, shrinking initial download/parse/compile cost.
Detailed Explanation
Bundlers create separate chunks loaded via dynamic `import()` when a route or feature is activated. Benefits: faster startup, better caching of stable vendor chunks. Costs: waterfalls if poorly designed, layout shift if UI isn't reserved, complexity in prefetching. Prefetch/preload critical next routes. Measure with coverage and bundle analysis. Combine with tree-shaking and deleting dead code.
Example
button.onclick = async () => {
const { openModal } = await import('./modal.js');
openModal();
};Interview Tip
Warn about chunk waterfalls.
Common Mistake
Splitting into hundreds of tiny chunks that hurt HTTP/caching efficiency.