Code splitting#

This page is informational only; if your app is using a compatible version of webpack code splitting, it's handled automatically.

Code splitting is used to break up a large JavaScript app into "chunks" that are loaded on demand, i.e. when the route/url changes.

For example, when you visit headless-render-api.com, you'll download ~150kb of JavaScript code for the React core functionality, and various front-page content. If you visit the /sign-in page, your browser will download another ~150kb of JavaScript for the authentication code.

Without code splitting all visitors would have to download 100% of the JavaScript app, even the parts they may never use, like authentication.

Example flow#

  1. visit example.com
  2. browser downloads main.js
  3. click a link to go to the /docs page
  4. JavaScript app on example.com appends <script src="/chunk.1.js"></script> into <head></head>
  5. after ~100ms the browser finishes downloading chunk.1.js and the new content loads

The chunk.1.js script will look something like:

webpackJsonp([1], {
  33: function() {},
  1337: function() {}
})

This is jsonp and that webpackJsonp function was defined in your main.js so chunk.1.js can reference it when it eventually loads.

The problem#

This is a problem for server-side rendering done in a headless browser (e.g. service.headless-render-api.com) - because the server-side rendered page will come down with <script src="/chunk.1.js"></script> before webpackJsonp is defined (main.js) which results in: Uncaught ReferenceError: webpackJsonp is not defined.

How we solve it#

  1. inject a fake webpackJsonp function at the beginning of the document to cache any calls made before it's officially defined
  2. move all chunks (e.g.: <script src="/chunk.1.js"></script>) from <head></head> to AFTER the "critical path" of HTML in the <body></body>
  3. inject a second function that monkey patches the now official webpackJsonp so it also flushes any cached calls.

To conclude, this achieves 2 things:

  1. a fix for the webpackJsonp is not defined error
  2. a fast "first meaningful paint" by placing the chunks after the critical path HTML