Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readReact

Preload a font and initialize a script

Use preload for a font and preinit for a classic script that can execute as soon as it downloads.

A map route needs a heading font and a classic script. Use React's resource APIs to start both downloads during rendering. Choose the script API based on when the code can run.

Fetch the font and start the script

Use preload for a font and keep the matching @font-face rule. The hint can start the request. The CSS still tells the browser where to use the font.

Use preinit for a classic script that can execute as soon as it downloads. That second part matters if the script installs listeners or expects markup to exist. A preload is a better fit if you plan to load and execute the script at a later point.

import { preinit, preload } from 'react-dom'

export default function MapRoute() {
  preload('/fonts/atlas.woff2', {
    as: 'font',
    type: 'font/woff2',
    crossOrigin: 'anonymous',
  })

  preinit('/map-runtime.js', { as: 'script' })

  return <h1 className="map-heading">Trail map</h1>
}

In the document head you get a font preload link with crossorigin="" and an async script for /map-runtime.js.

Serve the two files at those URLs. Point the heading's @font-face rule at the same font URL and apply its font family to .map-heading. Fonts use an anonymous CORS fetch, so keep crossOrigin on the hint even when the file lives on your origin. For the script, remove any second loader for that same job and check that its startup code can run before the map is mounted.

Check which request the browser uses

Open Network and reload the route in a fresh browser context. Filter by atlas.woff2 and look for a single font request. If the CSS fetches it again, check the URL and request mode on both entries. A preload whose request settings differ from the eventual resource load can leave you paying for two requests.

Load a route without a map to check that the app shell hasn't started the download there. If execution needs to wait for a click, use preload for the fetch and start the script in the click handler.