Unverified Commit b6f6179d authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

@next/font: Add preconnect tag when fonts are used but not preloaded in app-dir (#44746)

Add a preconnect tag to self with `crossorigin=anonymous` if fonts are used but not preloaded. This is already done in [`/pages`](https://github.com/vercel/next.js/blob/canary/packages/next/src/pages/_document.tsx#L384) but not yet for `/app`. 

Fixes NEXT-337

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 24a531a6
...@@ -762,25 +762,28 @@ function getPreloadedFontFilesInlineLinkTags( ...@@ -762,25 +762,28 @@ function getPreloadedFontFilesInlineLinkTags(
fontLoaderManifest: FontLoaderManifest | undefined, fontLoaderManifest: FontLoaderManifest | undefined,
serverCSSForEntries: string[], serverCSSForEntries: string[],
filePath?: string filePath?: string
): string[] { ): string[] | null {
if (!fontLoaderManifest || !filePath) { if (!fontLoaderManifest || !filePath) {
return [] return null
} }
const layoutOrPageCss = const layoutOrPageCss =
serverCSSManifest[filePath] || serverCSSManifest[filePath] ||
serverComponentManifest.__client_css_manifest__?.[filePath] serverComponentManifest.__client_css_manifest__?.[filePath]
if (!layoutOrPageCss) { if (!layoutOrPageCss) {
return [] return null
} }
const fontFiles = new Set<string>() const fontFiles = new Set<string>()
// If we find an entry in the manifest but it's empty, add a preconnect tag
let foundFontUsage = false
for (const css of layoutOrPageCss) { for (const css of layoutOrPageCss) {
// We only include the CSS if it is used by this entrypoint. // We only include the CSS if it is used by this entrypoint.
if (serverCSSForEntries.includes(css)) { if (serverCSSForEntries.includes(css)) {
const preloadedFontFiles = fontLoaderManifest.app[css] const preloadedFontFiles = fontLoaderManifest.app[css]
if (preloadedFontFiles) { if (preloadedFontFiles) {
foundFontUsage = true
for (const fontFile of preloadedFontFiles) { for (const fontFile of preloadedFontFiles) {
fontFiles.add(fontFile) fontFiles.add(fontFile)
} }
...@@ -788,6 +791,10 @@ function getPreloadedFontFilesInlineLinkTags( ...@@ -788,6 +791,10 @@ function getPreloadedFontFilesInlineLinkTags(
} }
} }
if (!foundFontUsage) {
return null
}
return [...fontFiles] return [...fontFiles]
} }
...@@ -1422,19 +1429,24 @@ export async function renderToHTMLOrFlight( ...@@ -1422,19 +1429,24 @@ export async function renderToHTMLOrFlight(
Component: () => { Component: () => {
return ( return (
<> <>
{preloadedFontFiles.map((fontFile) => { {preloadedFontFiles?.length === 0 ? (
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(fontFile)![1] <link rel="preconnect" href="/" crossOrigin="anonymous" />
return ( ) : null}
<link {preloadedFontFiles
key={fontFile} ? preloadedFontFiles.map((fontFile) => {
rel="preload" const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(fontFile)![1]
href={`${assetPrefix}/_next/${fontFile}`} return (
as="font" <link
type={`font/${ext}`} key={fontFile}
crossOrigin="anonymous" rel="preload"
/> href={`${assetPrefix}/_next/${fontFile}`}
) as="font"
})} type={`font/${ext}`}
crossOrigin="anonymous"
/>
)
})
: null}
{stylesheets {stylesheets
? stylesheets.map((href, index) => ( ? stylesheets.map((href, index) => (
<link <link
......
export default function Root({ children }) {
return (
<html>
<head>
<title>Hello World</title>
</head>
<body>{children}</body>
</html>
)
}
import styles from './styles.module.css'
export default function Page() {
return (
<>
<p className={styles.p}>hello world</p>
</>
)
}
import localFont from '@next/font/local'
const componentFont = localFont({ src: './comp.woff2', preload: false })
export default function Component() {
return (
<p className={componentFont.className}>{JSON.stringify(componentFont)}</p>
)
}
import Comp from './comp'
export default function Page() {
return <Comp />
}
import localFont from '@next/font/local'
const layoutFont = localFont({ src: './layout.woff2', preload: false })
export default function Layout({ children }) {
return (
<>
<p className={layoutFont.className}>{JSON.stringify(layoutFont)}</p>
{children}
</>
)
}
'use client'
import localFont from '@next/font/local'
const pageFont = localFont({ src: './page.woff2', preload: false })
export default function Page() {
return (
<>
<p className={pageFont.className}>{JSON.stringify(pageFont)}</p>
</>
)
}
import { font3 } from '../fonts' import { font3 } from '../../fonts'
export default function Component() { export default function Component() {
return ( return (
......
'use client' 'use client'
import { font6 } from '../../fonts' import { font6 } from '../../../fonts'
export default function Component() { export default function Component() {
return ( return (
......
'use client' 'use client'
import { font4 } from '../../fonts' import { font4 } from '../../../fonts'
export default function Root({ children }) { export default function Root({ children }) {
return ( return (
......
'use client' 'use client'
import Comp from './Comp' import Comp from './Comp'
import { font5 } from '../../fonts' import { font5 } from '../../../fonts'
export default function HomePage() { export default function HomePage() {
return ( return (
......
import { font1 } from '../fonts' import { font1 } from '../../fonts'
export default function Root({ children }) { export default function Root({ children }) {
return ( return (
......
'use client'
export default function Layout({ children }) { export default function Layout({ children }) {
return children return children
} }
import Comp from './Comp' import Comp from './Comp'
import { font1, font2 } from '../fonts' import { font1, font2 } from '../../fonts'
export default function HomePage() { export default function HomePage() {
return ( return (
......
...@@ -325,6 +325,29 @@ createNextDescribe( ...@@ -325,6 +325,29 @@ createNextDescribe(
}) })
}) })
}) })
describe('preconnect', () => {
it.each([['page'], ['layout'], ['component']])(
'should add preconnect when preloading is disabled in %s',
async (type: string) => {
const $ = await next.render$(`/preconnect-${type}`)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(1)
// Preload
expect($('link[as="font"]').length).toBe(0)
}
)
it('should not preconnect when css is used but no fonts', async () => {
const $ = await next.render$('/no-preconnect')
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
// Preload
expect($('link[as="font"]').length).toBe(0)
})
})
} }
if (isDev) { if (isDev) {
......
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