Referencing chunks to be prefetched

The previous section accounts for how chunks handled by Webpack are referenced in the page HTML for the current page. But what about subsequent navigation to other pages, which need to be able to load any required JavaScript or CSS assets instantaneously? When the current page has finished loading, Gatsby’s work isn’t done; it proceeds down the page to find any links that will benefit from prefetching.

NOTE

For an introduction to this concept, consult the Mozilla Developer Network’s guide to prefetching.

When Gatsby’s browser runtime encounters a <link rel="prefetch" href="..." /> element, it begins to download the resource at a low priority, and solely when all resources required for the currently active page are done loading. At this point in the app, we come full circle to one of the first concepts introduced: the <Link /> component. Once the <Link /> component’s componentDidMount callback is called, Gatsby automatically enqueues the destination path into the production-app.js file’s loader for prefetching.

Gatsby is now aware of the target page for each link to be prefetched as well as the componentChunkName and jsonName associated with it, but it still needs to know which chunk group is required for the component. To resolve this, the static-entry.js file requires the chunk-map.json file, which it injects it directly into the CDATA section of the HTML page for the current page under window.___chunkMapping so any production-app.js code can reference it, as follows:

<![
  CDATA[ */
    window.___chunkMapping={
      "app":[
        "/app-2e49587d85e03a033f58.js"
      ],
      "component---src-blog-2-js": [
        "/component---src-blog-2-js-cebc3ae7596cbb5b0951.css",
        "/component---src-blog-2-js-860f9fbc5c3881586b5d.js"
      ]
    }
  */ ]
]>

Thanks to this information, the production-app.js loader can now derive the full component asset path and dynamically generate a <link rel="prefetch" ... /> element in prefetch.js, thereupon injecting it into the DOM for the browser to handle appropriately. This is how Gatsby enables one of its most compelling features: instantaneous navigation between its pages.

NOTE

Prefetching can be disabled by implementing the disableCorePrefetching browser API in Gatsby and returning true.


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *