Trung BìnhPerformance iconPerformance

Code splitting là gì? Các chiến lược code splitting trong web apps?

Route-based code splitting là chiến lược đầu tiên — mỗi route là chunk riêng; dùng bundle analyzer để tìm large deps có alternatives nhỏ hơn; prefetch chunks cho next likely navigation.

  • Code splitting chia bundle thành chunks nhỏ hơn — load initial chunk nhỏ hơn, load thêm chunks on demand.
  • Dynamic import() là foundation: import('./module') trả về Promise, bundler tự tạo separate chunk.
  • Chiến lược: Route-based splitting — mỗi route là chunk riêng, user chỉ download code cho route đang visit; pattern chuẩn với React Router và React.lazy().
  • Component-based splitting — lazy load heavy components (rich text editor, PDF viewer, 3D rendering) chỉ khi cần.
  • Vendor splitting: tách node_modules thành vendor chunk — ít thay đổi hơn app code, cache lâu hơn; Vite tự động split vendor; Webpack SplitChunksPlugin cấu hình.
  • Shared chunks: code dùng ở nhiều routes tách thành shared chunk — tránh duplicate code trong nhiều chunks.
  • Prefetching và preloading: <link rel='prefetch'> cho next likely navigation (browser idle), <link rel='preload'> cho current route critical resources; Webpack magic comments: import(/ webpackPrefetch: true / './NextPage').
  • Analysis: Webpack Bundle Analyzer, vite-bundle-visualizer, source-map-explorer để xem chunk composition và identify optimization opportunities.

Pitfall: quá nhiều chunks nhỏ tệ hơn một chunk lớn do HTTP request overhead — HTTP/2 multiplexing giảm vấn đề này nhưng có limits.

Xem toàn bộ Performance cùng filter theo level & chủ đề con.

Mở danh sách Performance