Unverified Commit 4f5f4769 authored by Josh Story's avatar Josh Story Committed by GitHub

preload fonts using ReactDOM.preload (#48931)

This PR updates the way we preload fonts. Previously we tracked which
fonts we needed to preload for each layer and rendered a `<link
rel="preload" href="..." as="font" />` tag for each preloadable font.
This unfortunately gets blocked by data fetching and we want to be able
to hint these preloads as soon as possible. Now that React support Float
methods in RSC we can use `ReactDOM.preload(..., { as: "font" })` to
implement this functionality

This PR makes the following changes
1. expose a `preloadFont` method through the RSC graph
2. expose a `preconnect` metho through the RSC graph
3. refactor the preloads generation to use `preloadFont` instead of
rendering a preload link
4. If there are no fonts to preload but fonts are being used in CSS then
a `preconnect` asset origin is called instead of rendering a preconnect
link
5. instead of emitting a data attribute per font preload indicating
whether the project is using size-adjust we now emit a single global
meta tag. In the future we may get more granular about which fonts are
being size adjusted. In the meantime the current hueristic is to add
`-s` to the filename so it can still be inferred.

In the process of completing this work I discovered there were some bugs
in how the preconnect logic was originally implemented. Previously it
was possible to get multiple preconnects per render. Additionally the
preconnect href was always `"/"` which is not correct if you are hosting
your fonts at a CDN. The refactor fixed both of these issues

I want to do a larger refactor of the asset loading logic in App-Render
but I'll save that for a couple weeks from now

Additionally, the serialized output of preloads now omits the word
anonymous when using crossorigin so tests were updated to reflect
`crossorigin=""`

Additionally, tests were updated to no longer look for the size-adjust
data attribute on preloads

Additionally, There is a note about leaving a `{null}` render in place
to avoid a conflict with how the router models lazy trees. I'll follow
up with a PR addressing this
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 799a05ce
...@@ -18,4 +18,8 @@ export { ...@@ -18,4 +18,8 @@ export {
renderToReadableStream, renderToReadableStream,
decodeReply, decodeReply,
} from 'next/dist/compiled/react-server-dom-webpack/server.edge' } from 'next/dist/compiled/react-server-dom-webpack/server.edge'
export { preloadStyle } from 'next/dist/server/app-render/rsc/preloads' export {
preloadStyle,
preloadFont,
preconnect,
} from 'next/dist/server/app-render/rsc/preloads'
...@@ -594,7 +594,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -594,7 +594,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
export { renderToReadableStream, decodeReply } from 'next/dist/compiled/react-server-dom-webpack/server.edge' export { renderToReadableStream, decodeReply } from 'next/dist/compiled/react-server-dom-webpack/server.edge'
export const __next_app_webpack_require__ = __webpack_require__ export const __next_app_webpack_require__ = __webpack_require__
export { preloadStyle } from 'next/dist/server/app-render/rsc/preloads' export { preloadStyle, preloadFont, preconnect } from 'next/dist/server/app-render/rsc/preloads'
` `
return result return result
......
...@@ -9,6 +9,7 @@ import type { ...@@ -9,6 +9,7 @@ import type {
RenderOpts, RenderOpts,
Segment, Segment,
} from './types' } from './types'
import type { StaticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage' import type { StaticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage'
import type { StaticGenerationBailout } from '../../client/components/static-generation-bailout' import type { StaticGenerationBailout } from '../../client/components/static-generation-bailout'
import type { RequestAsyncStorage } from '../../client/components/request-async-storage' import type { RequestAsyncStorage } from '../../client/components/request-async-storage'
...@@ -60,7 +61,7 @@ import { getShortDynamicParamType } from './get-short-dynamic-param-type' ...@@ -60,7 +61,7 @@ import { getShortDynamicParamType } from './get-short-dynamic-param-type'
import { getSegmentParam } from './get-segment-param' import { getSegmentParam } from './get-segment-param'
import { getCssInlinedLinkTags } from './get-css-inlined-link-tags' import { getCssInlinedLinkTags } from './get-css-inlined-link-tags'
import { getServerCSSForEntries } from './get-server-css-for-entries' import { getServerCSSForEntries } from './get-server-css-for-entries'
import { getPreloadedFontFilesInlineLinkTags } from './get-preloaded-font-files-inline-link-tags' import { getPreloadableFonts } from './get-preloadable-fonts'
import { getScriptNonceFromHeader } from './get-script-nonce-from-header' import { getScriptNonceFromHeader } from './get-script-nonce-from-header'
import { renderToString } from './render-to-string' import { renderToString } from './render-to-string'
import { parseAndValidateFlightRouterState } from './parse-and-validate-flight-router-state' import { parseAndValidateFlightRouterState } from './parse-and-validate-flight-router-state'
...@@ -155,6 +156,8 @@ export async function renderToHTMLOrFlight( ...@@ -155,6 +156,8 @@ export async function renderToHTMLOrFlight(
nextConfigOutput, nextConfigOutput,
} = renderOpts } = renderOpts
const appUsingSizeAdjust = nextFontManifest?.appUsingSizeAdjust
const clientReferenceManifest = renderOpts.clientReferenceManifest! const clientReferenceManifest = renderOpts.clientReferenceManifest!
const serverCSSManifest = renderOpts.serverCSSManifest! const serverCSSManifest = renderOpts.serverCSSManifest!
...@@ -406,10 +409,7 @@ export async function renderToHTMLOrFlight( ...@@ -406,10 +409,7 @@ export async function renderToHTMLOrFlight(
layoutOrPagePath: string | undefined layoutOrPagePath: string | undefined
injectedCSS: Set<string> injectedCSS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
}): { }): React.ReactNode => {
styles: React.ReactNode
preloads: React.ReactNode
} => {
const stylesheets: string[] = layoutOrPagePath const stylesheets: string[] = layoutOrPagePath
? getCssInlinedLinkTags( ? getCssInlinedLinkTags(
clientReferenceManifest, clientReferenceManifest,
...@@ -422,49 +422,35 @@ export async function renderToHTMLOrFlight( ...@@ -422,49 +422,35 @@ export async function renderToHTMLOrFlight(
: [] : []
const preloadedFontFiles = layoutOrPagePath const preloadedFontFiles = layoutOrPagePath
? getPreloadedFontFilesInlineLinkTags( ? getPreloadableFonts(
serverCSSManifest!, serverCSSManifest!,
nextFontManifest, nextFontManifest,
serverCSSForEntries, serverCSSForEntries,
layoutOrPagePath, layoutOrPagePath,
injectedFontPreloadTagsWithCurrentLayout injectedFontPreloadTagsWithCurrentLayout
) )
: [] : null
const preloads = ( if (preloadedFontFiles) {
<> if (preloadedFontFiles.length) {
{preloadedFontFiles?.length === 0 ? ( for (let i = 0; i < preloadedFontFiles.length; i++) {
<> const fontFilename = preloadedFontFiles[i]
<link const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(fontFilename)![1]
data-next-font={ const type = `font/${ext}`
nextFontManifest?.appUsingSizeAdjust ? 'size-adjust' : '' const href = `${assetPrefix}/_next/${fontFilename}`
} ComponentMod.preloadFont(href, type)
rel="preconnect" }
href="/" } else {
crossOrigin="anonymous" try {
/> let url = new URL(assetPrefix)
</> ComponentMod.preconnect(url.origin, 'anonymous')
) : null} } catch (error) {
{preloadedFontFiles // assetPrefix must not be a fully qualified domain name. We assume
? preloadedFontFiles.map((fontFile) => { // we should preconnect to same origin instead
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(fontFile)![1] ComponentMod.preconnect('/', 'anonymous')
return ( }
<link }
key={fontFile} }
rel="preload"
href={`${assetPrefix}/_next/${fontFile}`}
as="font"
type={`font/${ext}`}
crossOrigin="anonymous"
data-next-font={
fontFile.includes('-s') ? 'size-adjust' : ''
}
/>
)
})
: null}
</>
)
const styles = stylesheets const styles = stylesheets
? stylesheets.map((href, index) => { ? stylesheets.map((href, index) => {
...@@ -493,10 +479,7 @@ export async function renderToHTMLOrFlight( ...@@ -493,10 +479,7 @@ export async function renderToHTMLOrFlight(
}) })
: null : null
return { return styles
styles,
preloads,
}
} }
const parseLoaderTree = (tree: LoaderTree) => { const parseLoaderTree = (tree: LoaderTree) => {
...@@ -560,7 +543,7 @@ export async function renderToHTMLOrFlight( ...@@ -560,7 +543,7 @@ export async function renderToHTMLOrFlight(
injectedFontPreloadTags injectedFontPreloadTags
) )
const { styles, preloads } = getLayerAssets({ const styles = getLayerAssets({
layoutOrPagePath, layoutOrPagePath,
injectedCSS: injectedCSSWithCurrentLayout, injectedCSS: injectedCSSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
...@@ -911,7 +894,15 @@ export async function renderToHTMLOrFlight( ...@@ -911,7 +894,15 @@ export async function renderToHTMLOrFlight(
) : ( ) : (
<Component {...props} /> <Component {...props} />
)} )}
{preloads} {/* This null is currently critical. The wrapped Component can render null and if there was not fragment
surrounding it this would look like a pending tree data state on the client which will cause an errror
and break the app. Long-term we need to move away from using null as a partial tree identifier since it
is a valid return type for the components we wrap. Once we make this change we can safely remove the
fragment. The reason the extra null here is required is that fragments which only have 1 child are elided.
If the Component above renders null the actual treedata will look like `[null, null]`. If we remove the extra
null it will look like `null` (the array is elided) and this is what confuses the client router.
TODO-APP update router to use a Symbol for partial tree detection */}
{null}
</> </>
) )
}, },
...@@ -1040,7 +1031,7 @@ export async function renderToHTMLOrFlight( ...@@ -1040,7 +1031,7 @@ export async function renderToHTMLOrFlight(
const { layoutOrPagePath } = const { layoutOrPagePath } =
parseLoaderTree(loaderTreeToFilter) parseLoaderTree(loaderTreeToFilter)
const { styles } = getLayerAssets({ const styles = getLayerAssets({
layoutOrPagePath, layoutOrPagePath,
injectedCSS: new Set(injectedCSS), injectedCSS: new Set(injectedCSS),
injectedFontPreloadTags: new Set(injectedFontPreloadTags), injectedFontPreloadTags: new Set(injectedFontPreloadTags),
...@@ -1074,7 +1065,7 @@ export async function renderToHTMLOrFlight( ...@@ -1074,7 +1065,7 @@ export async function renderToHTMLOrFlight(
injectedCSSWithCurrentLayout, injectedCSSWithCurrentLayout,
true true
) )
getPreloadedFontFilesInlineLinkTags( getPreloadableFonts(
serverCSSManifest!, serverCSSManifest!,
nextFontManifest, nextFontManifest,
serverCSSForEntries, serverCSSForEntries,
...@@ -1155,6 +1146,7 @@ export async function renderToHTMLOrFlight( ...@@ -1155,6 +1146,7 @@ export async function renderToHTMLOrFlight(
searchParams={providedSearchParams} searchParams={providedSearchParams}
getDynamicParamFromSegment={getDynamicParamFromSegment} getDynamicParamFromSegment={getDynamicParamFromSegment}
/> />
{appUsingSizeAdjust ? <meta name="next-size-adjust" /> : null}
</> </>
), ),
injectedCSS: new Set(), injectedCSS: new Set(),
...@@ -1292,6 +1284,7 @@ export async function renderToHTMLOrFlight( ...@@ -1292,6 +1284,7 @@ export async function renderToHTMLOrFlight(
searchParams={providedSearchParams} searchParams={providedSearchParams}
getDynamicParamFromSegment={getDynamicParamFromSegment} getDynamicParamFromSegment={getDynamicParamFromSegment}
/> />
{appUsingSizeAdjust ? <meta name="next-size-adjust" /> : null}
</> </>
} }
globalErrorComponent={GlobalError} globalErrorComponent={GlobalError}
...@@ -1499,6 +1492,7 @@ export async function renderToHTMLOrFlight( ...@@ -1499,6 +1492,7 @@ export async function renderToHTMLOrFlight(
searchParams={providedSearchParams} searchParams={providedSearchParams}
getDynamicParamFromSegment={getDynamicParamFromSegment} getDynamicParamFromSegment={getDynamicParamFromSegment}
/> />
{appUsingSizeAdjust ? <meta name="next-size-adjust" /> : null}
</head> </head>
<body></body> <body></body>
</html> </html>
......
...@@ -5,7 +5,7 @@ import { ...@@ -5,7 +5,7 @@ import {
import { getClientReferenceModuleKey } from '../../lib/client-reference' import { getClientReferenceModuleKey } from '../../lib/client-reference'
/** /**
* Get inline <link> tags based on server CSS manifest. Only used when rendering to HTML. * Get external stylesheet link hrefs based on server CSS manifest.
*/ */
export function getCssInlinedLinkTags( export function getCssInlinedLinkTags(
clientReferenceManifest: ClientReferenceManifest, clientReferenceManifest: ClientReferenceManifest,
......
...@@ -2,9 +2,13 @@ import { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest ...@@ -2,9 +2,13 @@ import { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest
import { ClientCSSReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' import { ClientCSSReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
/** /**
* Get inline <link rel="preload" as="font"> tags based on server CSS manifest and next/font manifest. Only used when rendering to HTML. * Get hrefs for fonts to preload
* Returns null if there are no fonts at all.
* Returns string[] if there are fonts to preload (font paths)
* Returns empty string[] if there are fonts but none to preload and no other fonts have been preloaded
* Returns null if there are fonts but none to preload and at least some were previously preloaded
*/ */
export function getPreloadedFontFilesInlineLinkTags( export function getPreloadableFonts(
serverCSSManifest: ClientCSSReferenceManifest, serverCSSManifest: ClientCSSReferenceManifest,
nextFontManifest: NextFontManifest | undefined, nextFontManifest: NextFontManifest | undefined,
serverCSSForEntries: string[], serverCSSForEntries: string[],
...@@ -39,15 +43,11 @@ export function getPreloadedFontFilesInlineLinkTags( ...@@ -39,15 +43,11 @@ export function getPreloadedFontFilesInlineLinkTags(
} }
} }
// If we find an entry in the manifest but it's empty, add a preconnect tag by returning null. if (fontFiles.size) {
// Only render a preconnect tag if we previously didn't preload any fonts. return [...fontFiles].sort()
if ( } else if (foundFontUsage && injectedFontPreloadTags.size === 0) {
!foundFontUsage || return []
(fontFiles.size === 0 && injectedFontPreloadTags.size > 0) } else {
) {
return null return null
} }
// Sorting to make order deterministic
return [...fontFiles].sort()
} }
...@@ -10,3 +10,15 @@ const stylePreloadOptions = { as: 'style' } ...@@ -10,3 +10,15 @@ const stylePreloadOptions = { as: 'style' }
export function preloadStyle(href: string) { export function preloadStyle(href: string) {
;(ReactDOM as any).preload(href, stylePreloadOptions) ;(ReactDOM as any).preload(href, stylePreloadOptions)
} }
export function preloadFont(href: string, type: string) {
;(ReactDOM as any).preload(href, { as: 'font', type })
}
export function preconnect(href: string, crossOrigin?: string) {
if (typeof crossOrigin === 'string') {
;(ReactDOM as any).preconnect(href, { crossOrigin })
} else {
;(ReactDOM as any).preconnect(href)
}
}
...@@ -235,27 +235,24 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { ...@@ -235,27 +235,24 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => {
expect(getAttrs($('link[as="font"]'))).toEqual([ expect(getAttrs($('link[as="font"]'))).toEqual([
{ {
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: '',
href: '/_next/static/media/b2104791981359ae-s.p.woff2', href: '/_next/static/media/b2104791981359ae-s.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
'data-next-font': 'size-adjust',
}, },
{ {
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: '',
href: '/_next/static/media/b61859a50be14c53-s.p.woff2', href: '/_next/static/media/b61859a50be14c53-s.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
'data-next-font': 'size-adjust',
}, },
{ {
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48-s.p.woff2', href: '/_next/static/media/e9b9dc0d8ba35f48-s.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
'data-next-font': 'size-adjust',
}, },
]) ])
}) })
...@@ -270,27 +267,24 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { ...@@ -270,27 +267,24 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => {
expect(getAttrs($('link[as="font"]'))).toEqual([ expect(getAttrs($('link[as="font"]'))).toEqual([
{ {
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: '',
href: '/_next/static/media/e1053f04babc7571-s.p.woff2', href: '/_next/static/media/e1053f04babc7571-s.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
'data-next-font': 'size-adjust',
}, },
{ {
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48-s.p.woff2', href: '/_next/static/media/e9b9dc0d8ba35f48-s.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
'data-next-font': 'size-adjust',
}, },
{ {
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: '',
href: '/_next/static/media/feab2c68f2a8e9a4-s.p.woff2', href: '/_next/static/media/feab2c68f2a8e9a4-s.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
'data-next-font': 'size-adjust',
}, },
]) ])
}) })
...@@ -305,19 +299,17 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { ...@@ -305,19 +299,17 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => {
expect(getAttrs($('link[as="font"]'))).toEqual([ expect(getAttrs($('link[as="font"]'))).toEqual([
{ {
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: '',
href: '/_next/static/media/75c5faeeb9c86969-s.p.woff2', href: '/_next/static/media/75c5faeeb9c86969-s.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
'data-next-font': 'size-adjust',
}, },
{ {
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48-s.p.woff2', href: '/_next/static/media/e9b9dc0d8ba35f48-s.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
'data-next-font': 'size-adjust',
}, },
]) ])
}) })
...@@ -332,19 +324,17 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { ...@@ -332,19 +324,17 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => {
expect(getAttrs($('link[as="font"]'))).toEqual([ expect(getAttrs($('link[as="font"]'))).toEqual([
{ {
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: '',
href: '/_next/static/media/568e4c6d8123c4d6-s.p.woff2', href: '/_next/static/media/568e4c6d8123c4d6-s.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
'data-next-font': 'size-adjust',
}, },
{ {
as: 'font', as: 'font',
crossorigin: 'anonymous', crossorigin: '',
href: '/_next/static/media/e9b9dc0d8ba35f48-s.p.woff2', href: '/_next/static/media/e9b9dc0d8ba35f48-s.p.woff2',
rel: 'preload', rel: 'preload',
type: 'font/woff2', type: 'font/woff2',
'data-next-font': 'size-adjust',
}, },
]) ])
}) })
...@@ -359,10 +349,9 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { ...@@ -359,10 +349,9 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => {
// Preconnect // Preconnect
expect($('link[rel="preconnect"]').length).toBe(1) expect($('link[rel="preconnect"]').length).toBe(1)
expect($('link[rel="preconnect"]').get(0).attribs).toEqual({ expect($('link[rel="preconnect"]').get(0).attribs).toEqual({
crossorigin: 'anonymous', crossorigin: '',
href: '/', href: '/',
rel: 'preconnect', rel: 'preconnect',
'data-next-font': 'size-adjust',
}) })
// Preload // Preload
expect($('link[as="font"]').length).toBe(0) expect($('link[as="font"]').length).toBe(0)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment