Unverified Commit fff183c4 authored by Janicklas Ralph's avatar Janicklas Ralph Committed by GitHub

Font optimization bug fix (#24162)



## Bug

- [x] Related issues linked using `fixes #23896`
- [x] Integration tests added

Fixes #23896
parent fc538790
...@@ -13,24 +13,9 @@ type postProcessOptions = { ...@@ -13,24 +13,9 @@ type postProcessOptions = {
type renderOptions = { type renderOptions = {
getFontDefinition?: (url: string) => string getFontDefinition?: (url: string) => string
} }
type PostProcessData = {
preloads: {
images: Array<string>
}
}
interface PostProcessMiddleware { interface PostProcessMiddleware {
inspect: ( inspect: (originalDom: HTMLElement, options: renderOptions) => any
originalDom: HTMLElement, mutate: (markup: string, data: any, options: renderOptions) => Promise<string>
data: PostProcessData,
options: renderOptions
) => void
mutate: (
markup: string,
data: PostProcessData,
options: renderOptions
) => Promise<string>
} }
type middlewareSignature = { type middlewareSignature = {
...@@ -58,18 +43,13 @@ async function processHTML( ...@@ -58,18 +43,13 @@ async function processHTML(
if (!middlewareRegistry[0]) { if (!middlewareRegistry[0]) {
return html return html
} }
const postProcessData: PostProcessData = {
preloads: {
images: [],
},
}
const root: HTMLElement = parse(html) const root: HTMLElement = parse(html)
let document = html let document = html
// Calls the middleware, with some instrumentation and logging // Calls the middleware, with some instrumentation and logging
async function callMiddleWare(middleware: PostProcessMiddleware) { async function callMiddleWare(middleware: PostProcessMiddleware) {
// let timer = Date.now() // let timer = Date.now()
middleware.inspect(root, postProcessData, data) const inspectData = middleware.inspect(root, data)
document = await middleware.mutate(document, postProcessData, data) document = await middleware.mutate(document, inspectData, data)
// timer = Date.now() - timer // timer = Date.now() - timer
// if (timer > MIDDLEWARE_TIME_BUDGET) { // if (timer > MIDDLEWARE_TIME_BUDGET) {
// TODO: Identify a correct upper limit for the postprocess step // TODO: Identify a correct upper limit for the postprocess step
...@@ -89,15 +69,11 @@ async function processHTML( ...@@ -89,15 +69,11 @@ async function processHTML(
} }
class FontOptimizerMiddleware implements PostProcessMiddleware { class FontOptimizerMiddleware implements PostProcessMiddleware {
fontDefinitions: (string | undefined)[][] = [] inspect(originalDom: HTMLElement, options: renderOptions) {
inspect(
originalDom: HTMLElement,
_data: PostProcessData,
options: renderOptions
) {
if (!options.getFontDefinition) { if (!options.getFontDefinition) {
return return
} }
const fontDefinitions: (string | undefined)[][] = []
// collecting all the requested font definitions // collecting all the requested font definitions
originalDom originalDom
.querySelectorAll('link') .querySelectorAll('link')
...@@ -115,30 +91,35 @@ class FontOptimizerMiddleware implements PostProcessMiddleware { ...@@ -115,30 +91,35 @@ class FontOptimizerMiddleware implements PostProcessMiddleware {
const nonce = element.getAttribute('nonce') const nonce = element.getAttribute('nonce')
if (url) { if (url) {
this.fontDefinitions.push([url, nonce]) fontDefinitions.push([url, nonce])
} }
}) })
return fontDefinitions
} }
mutate = async ( mutate = async (
markup: string, markup: string,
_data: PostProcessData, fontDefinitions: string[][],
options: renderOptions options: renderOptions
) => { ) => {
let result = markup let result = markup
if (!options.getFontDefinition) { if (!options.getFontDefinition) {
return markup return markup
} }
for (const key in this.fontDefinitions) {
const [url, nonce] = this.fontDefinitions[key] fontDefinitions.forEach((fontDef) => {
const [url, nonce] = fontDef
const fallBackLinkTag = `<link rel="stylesheet" href="${url}"/>` const fallBackLinkTag = `<link rel="stylesheet" href="${url}"/>`
if ( if (
result.indexOf(`<style data-href="${url}">`) > -1 || result.indexOf(`<style data-href="${url}">`) > -1 ||
result.indexOf(fallBackLinkTag) > -1 result.indexOf(fallBackLinkTag) > -1
) { ) {
// The font is already optimized and probably the response is cached // The font is already optimized and probably the response is cached
continue return
} }
const fontContent = options.getFontDefinition(url as string) const fontContent = options.getFontDefinition
? options.getFontDefinition(url as string)
: null
if (!fontContent) { if (!fontContent) {
/** /**
* In case of unreachable font definitions, fallback to default link tag. * In case of unreachable font definitions, fallback to default link tag.
...@@ -151,13 +132,15 @@ class FontOptimizerMiddleware implements PostProcessMiddleware { ...@@ -151,13 +132,15 @@ class FontOptimizerMiddleware implements PostProcessMiddleware {
`<style data-href="${url}"${nonceStr}>${fontContent}</style></head>` `<style data-href="${url}"${nonceStr}>${fontContent}</style></head>`
) )
} }
} })
return result return result
} }
} }
class ImageOptimizerMiddleware implements PostProcessMiddleware { class ImageOptimizerMiddleware implements PostProcessMiddleware {
inspect(originalDom: HTMLElement, _data: PostProcessData) { inspect(originalDom: HTMLElement) {
const imgPreloads = []
const imgElements = originalDom.querySelectorAll('img') const imgElements = originalDom.querySelectorAll('img')
let eligibleImages: Array<HTMLElement> = [] let eligibleImages: Array<HTMLElement> = []
for (let i = 0; i < imgElements.length; i++) { for (let i = 0; i < imgElements.length; i++) {
...@@ -169,18 +152,18 @@ class ImageOptimizerMiddleware implements PostProcessMiddleware { ...@@ -169,18 +152,18 @@ class ImageOptimizerMiddleware implements PostProcessMiddleware {
} }
} }
_data.preloads.images = []
for (const imgEl of eligibleImages) { for (const imgEl of eligibleImages) {
const src = imgEl.getAttribute('src') const src = imgEl.getAttribute('src')
if (src) { if (src) {
_data.preloads.images.push(src) imgPreloads.push(src)
} }
} }
return imgPreloads
} }
mutate = async (markup: string, _data: PostProcessData) => { mutate = async (markup: string, imgPreloads: string[]) => {
let result = markup let result = markup
let imagePreloadTags = _data.preloads.images let imagePreloadTags = imgPreloads
.filter((imgHref) => !preloadTagAlreadyExists(markup, imgHref)) .filter((imgHref) => !preloadTagAlreadyExists(markup, imgHref))
.reduce( .reduce(
(acc, imgHref) => (acc, imgHref) =>
......
import Head from 'next/head'
import Link from 'next/link'
const WithFont = () => {
return (
<>
<Head>
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700;900&display=swap"
rel="stylesheet"
/>
</Head>
<div>
Page with custom fonts
<br />
<br />
<Link href="/without-font">Without font</Link>
</div>
</>
)
}
export const getServerSideProps = async () => {
return {
props: {},
}
}
export default WithFont
import Head from 'next/head'
import Link from 'next/link'
const WithoutFont = () => {
return (
<>
<Head>
<meta name="robots" content="noindex, nofollow" />
</Head>
<div>
Page without custom fonts
<br />
<br />
<Link href="/with-font">With font</Link>
</div>
</>
)
}
export const getServerSideProps = async () => {
return {
props: {},
}
}
export default WithoutFont
...@@ -102,6 +102,25 @@ function runTests() { ...@@ -102,6 +102,25 @@ function runTests() {
) )
}) })
it('should only inline included fonts per page', async () => {
const html = await renderViaHTTP(appPort, '/with-font')
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(html).toContain(
'<link rel="stylesheet" data-href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700;900&amp;display=swap"/>'
)
expect(html).toMatch(
/<style data-href="https:\/\/fonts\.googleapis\.com\/css2\?family=Roboto:wght@400;700;900&display=swap">.*<\/style>/
)
const htmlWithoutFont = await renderViaHTTP(appPort, '/without-font')
expect(htmlWithoutFont).not.toContain(
'<link rel="stylesheet" data-href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700;900&amp;display=swap"/>'
)
expect(htmlWithoutFont).not.toMatch(
/<style data-href="https:\/\/fonts\.googleapis\.com\/css2\?family=Roboto:wght@400;700;900&display=swap">.*<\/style>/
)
})
it.skip('should minify the css', async () => { it.skip('should minify the css', async () => {
const snapshotJson = JSON.parse( const snapshotJson = JSON.parse(
await fs.readFile(join(__dirname, 'manifest-snapshot.json'), { await fs.readFile(join(__dirname, 'manifest-snapshot.json'), {
......
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