Unverified Commit 58a4482f authored by Janicklas Ralph's avatar Janicklas Ralph Committed by GitHub

Font optimization add preconnect (#25346)

parent 1cb4aaa3
...@@ -106,7 +106,7 @@ export class FontStylesheetGatheringPlugin { ...@@ -106,7 +106,7 @@ export class FontStylesheetGatheringPlugin {
!props.rel || !props.rel ||
props.rel !== 'stylesheet' || props.rel !== 'stylesheet' ||
!props.href || !props.href ||
!OPTIMIZED_FONT_PROVIDERS.some((url) => !OPTIMIZED_FONT_PROVIDERS.some(({ url }) =>
props.href.startsWith(url) props.href.startsWith(url)
) )
) { ) {
......
...@@ -37,8 +37,9 @@ export const TEMPORARY_REDIRECT_STATUS = 307 ...@@ -37,8 +37,9 @@ export const TEMPORARY_REDIRECT_STATUS = 307
export const PERMANENT_REDIRECT_STATUS = 308 export const PERMANENT_REDIRECT_STATUS = 308
export const STATIC_PROPS_ID = '__N_SSG' export const STATIC_PROPS_ID = '__N_SSG'
export const SERVER_PROPS_ID = '__N_SSP' export const SERVER_PROPS_ID = '__N_SSP'
export const GOOGLE_FONT_PROVIDER = 'https://fonts.googleapis.com/css'
export const OPTIMIZED_FONT_PROVIDERS = [ export const OPTIMIZED_FONT_PROVIDERS = [
'https://fonts.googleapis.com/css', { url: GOOGLE_FONT_PROVIDER, preconnect: 'https://fonts.gstatic.com' },
'https://use.typekit.net/', { url: 'https://use.typekit.net', preconnect: 'https://use.typekit.net' },
] ]
export const STATIC_STATUS_PAGES = ['/500'] export const STATIC_STATUS_PAGES = ['/500']
...@@ -82,7 +82,7 @@ class FontOptimizerMiddleware implements PostProcessMiddleware { ...@@ -82,7 +82,7 @@ class FontOptimizerMiddleware implements PostProcessMiddleware {
(tag: HTMLElement) => (tag: HTMLElement) =>
tag.getAttribute('rel') === 'stylesheet' && tag.getAttribute('rel') === 'stylesheet' &&
tag.hasAttribute('data-href') && tag.hasAttribute('data-href') &&
OPTIMIZED_FONT_PROVIDERS.some((url) => { OPTIMIZED_FONT_PROVIDERS.some(({ url }) => {
const dataHref = tag.getAttribute('data-href') const dataHref = tag.getAttribute('data-href')
return dataHref ? dataHref.startsWith(url) : false return dataHref ? dataHref.startsWith(url) : false
}) })
...@@ -104,6 +104,8 @@ class FontOptimizerMiddleware implements PostProcessMiddleware { ...@@ -104,6 +104,8 @@ class FontOptimizerMiddleware implements PostProcessMiddleware {
options: renderOptions options: renderOptions
) => { ) => {
let result = markup let result = markup
let preconnectUrls = new Set<string>()
if (!options.getFontDefinition) { if (!options.getFontDefinition) {
return markup return markup
} }
...@@ -132,9 +134,27 @@ class FontOptimizerMiddleware implements PostProcessMiddleware { ...@@ -132,9 +134,27 @@ class FontOptimizerMiddleware implements PostProcessMiddleware {
'</head>', '</head>',
`<style data-href="${url}"${nonceStr}>${fontContent}</style></head>` `<style data-href="${url}"${nonceStr}>${fontContent}</style></head>`
) )
const provider = OPTIMIZED_FONT_PROVIDERS.find((p) =>
url.startsWith(p.url)
)
if (provider) {
preconnectUrls.add(provider.preconnect)
}
} }
}) })
let preconnectTag = ''
preconnectUrls.forEach((url) => {
preconnectTag += `<link rel="preconnect" href="${url}" crossorigin />`
})
result = result.replace(
'<meta name="next-font-preconnect"/>',
preconnectTag
)
return result return result
} }
} }
......
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import { GOOGLE_FONT_PROVIDER } from '../lib/constants'
const https = require('https') const https = require('https')
const CHROME_UA = const CHROME_UA =
...@@ -10,6 +11,10 @@ export type FontManifest = Array<{ ...@@ -10,6 +11,10 @@ export type FontManifest = Array<{
content: string content: string
}> }>
function isGoogleFont(url: string): boolean {
return url.startsWith(GOOGLE_FONT_PROVIDER)
}
function getFontForUA(url: string, UA: string): Promise<String> { function getFontForUA(url: string, UA: string): Promise<String> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let rawData: any = '' let rawData: any = ''
...@@ -45,7 +50,9 @@ export async function getFontDefinitionFromNetwork( ...@@ -45,7 +50,9 @@ export async function getFontDefinitionFromNetwork(
* CSS cascading 🤷‍♂️. * CSS cascading 🤷‍♂️.
*/ */
try { try {
if (isGoogleFont(url)) {
result += await getFontForUA(url, IE_UA) result += await getFontForUA(url, IE_UA)
}
result += await getFontForUA(url, CHROME_UA) result += await getFontForUA(url, CHROME_UA)
} catch (e) { } catch (e) {
Log.warn( Log.warn(
......
...@@ -447,7 +447,9 @@ export class Head extends Component< ...@@ -447,7 +447,9 @@ export class Head extends Component<
if ( if (
c.type === 'link' && c.type === 'link' &&
c.props['href'] && c.props['href'] &&
OPTIMIZED_FONT_PROVIDERS.some((url) => c.props['href'].startsWith(url)) OPTIMIZED_FONT_PROVIDERS.some(({ url }) =>
c.props['href'].startsWith(url)
)
) { ) {
const newProps = { ...(c.props || {}) } const newProps = { ...(c.props || {}) }
newProps['data-href'] = newProps['href'] newProps['data-href'] = newProps['href']
...@@ -639,6 +641,9 @@ export class Head extends Component< ...@@ -639,6 +641,9 @@ export class Head extends Component<
</> </>
)} )}
{children} {children}
{process.env.__NEXT_OPTIMIZE_FONTS && (
<meta name="next-font-preconnect" />
)}
{head} {head}
<meta <meta
name="next-head-count" name="next-head-count"
......
import * as React from 'react' import * as React from 'react'
/// @ts-ignore /// @ts-ignore
import Document, { Main, NextScript, Head } from 'next/document' import Document, { Main, NextScript, Head } from 'next/document'
export default class MyDocument extends Document { export default class MyDocument extends Document {
constructor(props) { constructor(props) {
super(props) super(props)
......
[ [
{ {
"url": "https://use.typekit.net/plm1izr.css", "url": "https://use.typekit.net/plm1izr.css",
"content": "@import url(\"https://p.typekit.net/p.css?s=1&k=plm1izr&ht=tk&f=32266&a=23152309&app=typekit&e=css\");@font-face{font-family:\"birra-2\";src:url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:700}.tk-birra-2{font-family:\"birra-2\",serif}@import url(\"https://p.typekit.net/p.css?s=1&k=plm1izr&ht=tk&f=32266&a=23152309&app=typekit&e=css\");@font-face{font-family:\"birra-2\";src:url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:700}.tk-birra-2{font-family:\"birra-2\",serif}" "content": "@import url(\"https://p.typekit.net/p.css?s=1&k=plm1izr&ht=tk&f=32266&a=23152309&app=typekit&e=css\");@font-face{font-family:\"birra-2\";src:url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/23e0ad/00000000000000003b9b410c/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:700}.tk-birra-2{font-family:\"birra-2\",serif}"
}, },
{ {
"url": "https://use.typekit.net/ucs7mcf.css", "url": "https://use.typekit.net/ucs7mcf.css",
"content": "@import url(\"https://p.typekit.net/p.css?s=1&k=ucs7mcf&ht=tk&f=43886&a=23152309&app=typekit&e=css\");@font-face{font-family:\"flegrei\";src:url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:400}.tk-flegrei{font-family:\"flegrei\",sans-serif}@import url(\"https://p.typekit.net/p.css?s=1&k=ucs7mcf&ht=tk&f=43886&a=23152309&app=typekit&e=css\");@font-face{font-family:\"flegrei\";src:url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:400}.tk-flegrei{font-family:\"flegrei\",sans-serif}" "content": "@import url(\"https://p.typekit.net/p.css?s=1&k=ucs7mcf&ht=tk&f=43886&a=23152309&app=typekit&e=css\");@font-face{font-family:\"flegrei\";src:url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/74a5d1/00000000000000003b9b3d6e/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:400}.tk-flegrei{font-family:\"flegrei\",sans-serif}"
}, },
{ {
"url": "https://use.typekit.net/erd0sed.css", "url": "https://use.typekit.net/erd0sed.css",
"content": "@import url(\"https://p.typekit.net/p.css?s=1&k=erd0sed&ht=tk&f=43885&a=23152309&app=typekit&e=css\");@font-face{font-family:\"pantelleria\";src:url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:400}.tk-pantelleria{font-family:\"pantelleria\",sans-serif}@import url(\"https://p.typekit.net/p.css?s=1&k=erd0sed&ht=tk&f=43885&a=23152309&app=typekit&e=css\");@font-face{font-family:\"pantelleria\";src:url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:400}.tk-pantelleria{font-family:\"pantelleria\",sans-serif}" "content": "@import url(\"https://p.typekit.net/p.css?s=1&k=erd0sed&ht=tk&f=43885&a=23152309&app=typekit&e=css\");@font-face{font-family:\"pantelleria\";src:url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff2\"),url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"woff\"),url(\"https://use.typekit.net/af/1f141c/00000000000000003b9b3d6f/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3\") format(\"opentype\");font-display:auto;font-style:normal;font-weight:400}.tk-pantelleria{font-family:\"pantelleria\",sans-serif}"
} }
] ]
...@@ -54,6 +54,7 @@ describe('Font Optimization', () => { ...@@ -54,6 +54,7 @@ describe('Font Optimization', () => {
/<style data-href="https:\/\/fonts\.googleapis\.com\/css2\?family=Roboto:wght@700">.*<\/style>/, /<style data-href="https:\/\/fonts\.googleapis\.com\/css2\?family=Roboto:wght@700">.*<\/style>/,
/<style data-href="https:\/\/fonts.googleapis.com\/css2\?family=Roboto:wght@400;700;900&display=swap">.*<\/style>/, /<style data-href="https:\/\/fonts.googleapis.com\/css2\?family=Roboto:wght@400;700;900&display=swap">.*<\/style>/,
], ],
'https://fonts.gstatic.com',
], ],
[ [
'typekit', 'typekit',
...@@ -69,13 +70,15 @@ describe('Font Optimization', () => { ...@@ -69,13 +70,15 @@ describe('Font Optimization', () => {
/<style data-href="https:\/\/use.typekit.net\/ucs7mcf.css">.*<\/style>/, /<style data-href="https:\/\/use.typekit.net\/ucs7mcf.css">.*<\/style>/,
/<style data-href="https:\/\/use.typekit.net\/ucs7mcf.css">.*<\/style>/, /<style data-href="https:\/\/use.typekit.net\/ucs7mcf.css">.*<\/style>/,
], ],
'https://use.typekit.net',
], ],
])( ])(
'with-%s', 'with-%s',
( (
property, property,
[staticFont, staticHeadFont, starsFont, withFont], [staticFont, staticHeadFont, starsFont, withFont],
[staticPattern, staticHeadPattern, starsPattern, withFontPattern] [staticPattern, staticHeadPattern, starsPattern, withFontPattern],
preconnectUrl
) => { ) => {
const appDir = join(fixturesDir, `with-${property}`) const appDir = join(fixturesDir, `with-${property}`)
const nextConfig = join(appDir, 'next.config.js') const nextConfig = join(appDir, 'next.config.js')
...@@ -152,6 +155,14 @@ describe('Font Optimization', () => { ...@@ -152,6 +155,14 @@ describe('Font Optimization', () => {
expect(html).toMatch(starsPattern) expect(html).toMatch(starsPattern)
}) })
it(`should add preconnect tag`, async () => {
const html = await renderViaHTTP(appPort, '/stars')
const $ = cheerio.load(html)
expect(
$(`link[rel=preconnect][href="${preconnectUrl}"]`).length
).toBe(1)
})
it('should skip this optimization for AMP pages', async () => { it('should skip this optimization for AMP pages', async () => {
const html = await renderViaHTTP(appPort, '/amp') const html = await renderViaHTTP(appPort, '/amp')
const $ = cheerio.load(html) const $ = cheerio.load(html)
......
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