# Code splitting and bundling — Web Performance Optimization

Source: https://www.geekswithgeeks.com/en/web-performance/web-perf-09

> Split code into smaller chunks loaded on-demand to reduce initial bundle size and improve load performance.

## Dynamic imports for code splitting

Use `import()` for lazy loading: `const modal = await import('./modal.js')`. Webpack and other bundlers automatically create separate chunks. Load heavy features only when needed, not in initial bundle.

## Route-based code splitting

In single-page apps (React, Vue), split code per route. Load only JavaScript for current route. Frameworks like Next.js and Nuxt do this automatically. Reduces initial bundle by 50-70%.

## Bundle analysis and monitoring

Use tools like webpack-bundle-analyzer, Bundle Buddy, or Bundlephobia to visualize bundle composition. Set budget alerts: fail build if bundle exceeds size limit (e.g., 250KB gzipped).

## Bundle size best practices

Audit dependencies regularly. Prefer smaller alternatives. Use ESM-only packages. Monitor bundle growth in CI. Set strict size budgets (JavaScript <250KB, vendor <100KB gzipped).

Quick check

**Quiz:** What can route-based code splitting achieve?

- [ ] Reduces initial bundle by 50-70%
- [ ] Eliminates the need for caching
- [ ] Compresses assets automatically
