Unverified Commit 6ad91722 authored by Janicklas Ralph's avatar Janicklas Ralph Committed by GitHub

Font optimization bug fix (#24968)

parent b859c5bd
...@@ -100,6 +100,18 @@ export default function initHeadManager(): { ...@@ -100,6 +100,18 @@ export default function initHeadManager(): {
const tags: Record<string, JSX.Element[]> = {} const tags: Record<string, JSX.Element[]> = {}
head.forEach((h) => { head.forEach((h) => {
if (
// If the font tag is loaded only on client navigation
// it won't be inlined. In this case revert to the original behavior
h.type === 'link' &&
h.props['data-optimized-fonts'] &&
!document.querySelector(
`style[data-href="${h.props['data-href']}"]`
)
) {
h.props.href = h.props['data-href']
h.props['data-href'] = undefined
}
const components = tags[h.type] || [] const components = tags[h.type] || []
components.push(h) components.push(h)
tags[h.type] = components tags[h.type] = components
......
...@@ -155,6 +155,10 @@ function reduceComponents( ...@@ -155,6 +155,10 @@ function reduceComponents(
const newProps = { ...(c.props || {}) } const newProps = { ...(c.props || {}) }
newProps['data-href'] = newProps['href'] newProps['data-href'] = newProps['href']
newProps['href'] = undefined newProps['href'] = undefined
// Add this attribute to make it easy to identify optimized tags
newProps['data-optimized-fonts'] = true
return React.cloneElement(c, newProps) return React.cloneElement(c, newProps)
} }
} }
......
...@@ -108,7 +108,7 @@ describe('Build Output', () => { ...@@ -108,7 +108,7 @@ describe('Build Output', () => {
expect(parseFloat(err404FirstLoad)).toBeCloseTo(66.3, 0) expect(parseFloat(err404FirstLoad)).toBeCloseTo(66.3, 0)
expect(err404FirstLoad.endsWith('kB')).toBe(true) expect(err404FirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(sharedByAll)).toBeCloseTo(63.3, 1) expect(parseFloat(sharedByAll)).toBeCloseTo(63.4, 1)
expect(sharedByAll.endsWith('kB')).toBe(true) expect(sharedByAll.endsWith('kB')).toBe(true)
if (_appSize.endsWith('kB')) { if (_appSize.endsWith('kB')) {
...@@ -122,7 +122,7 @@ describe('Build Output', () => { ...@@ -122,7 +122,7 @@ describe('Build Output', () => {
expect(parseFloat(webpackSize) - 952).toBeLessThanOrEqual(0) expect(parseFloat(webpackSize) - 952).toBeLessThanOrEqual(0)
expect(webpackSize.endsWith(' B')).toBe(true) expect(webpackSize.endsWith(' B')).toBe(true)
expect(parseFloat(mainSize) - 19.3).toBeLessThanOrEqual(0) expect(parseFloat(mainSize) - 19.4).toBeLessThanOrEqual(0)
expect(mainSize.endsWith('kB')).toBe(true) expect(mainSize.endsWith('kB')).toBe(true)
expect(parseFloat(frameworkSize) - 42.1).toBeLessThanOrEqual(0) expect(parseFloat(frameworkSize) - 42.1).toBeLessThanOrEqual(0)
......
import React from 'react' import React from 'react'
import Link from 'next/link'
const Page = () => { const Page = () => {
return <div>Hi!</div> return (
<div>
Hi!
<br />
<br />
<Link href="/with-font">
<a id="with-font">With font</a>
</Link>
</div>
)
} }
export default Page export default Page
...@@ -11,7 +11,7 @@ const WithFont = () => { ...@@ -11,7 +11,7 @@ const WithFont = () => {
/> />
</Head> </Head>
<div> <div id="with-font-container">
Page with custom fonts Page with custom fonts
<br /> <br />
<br /> <br />
......
...@@ -20,18 +20,27 @@ const server = http.createServer(async (req, res) => { ...@@ -20,18 +20,27 @@ const server = http.createServer(async (req, res) => {
} }
if (pathname.startsWith('/_next/static/')) { if (pathname.startsWith('/_next/static/')) {
res.write( let prom = Promise.resolve()
fs.readFileSync( if (pathname.endsWith('.css')) {
path.join( prom = new Promise((resolve) => setTimeout(resolve, 20000))
__dirname, }
'./.next/static/', prom.then(() => {
decodeURI(pathname.slice('/_next/static/'.length)) res.write(
), fs.readFileSync(
'utf8' path.join(
__dirname,
'./.next/static/',
decodeURI(pathname.slice('/_next/static/'.length))
),
'utf8'
)
) )
) return res.end()
return res.end() })
} else { } else {
if (pathname === '') {
pathname = '/index'
}
const ext = isDataReq ? 'json' : 'html' const ext = isDataReq ? 'json' : 'html'
if ( if (
fs.existsSync( fs.existsSync(
......
import React from 'react' import React from 'react'
import Link from 'next/link'
const Page = () => { const Page = () => {
return <div>Hi!</div> return (
<div>
Hi!
<br />
<br />
<Link href="/with-font">
<a id="with-font">With font</a>
</Link>
</div>
)
} }
export default Page export default Page
...@@ -8,7 +8,7 @@ const WithFont = () => { ...@@ -8,7 +8,7 @@ const WithFont = () => {
<link href="https://use.typekit.net/ucs7mcf.css" rel="stylesheet" /> <link href="https://use.typekit.net/ucs7mcf.css" rel="stylesheet" />
</Head> </Head>
<div> <div id="with-font-container">
Page with custom fonts Page with custom fonts
<br /> <br />
<br /> <br />
......
...@@ -20,18 +20,27 @@ const server = http.createServer(async (req, res) => { ...@@ -20,18 +20,27 @@ const server = http.createServer(async (req, res) => {
} }
if (pathname.startsWith('/_next/static/')) { if (pathname.startsWith('/_next/static/')) {
res.write( let prom = Promise.resolve()
fs.readFileSync( if (pathname.endsWith('.css')) {
path.join( prom = new Promise((resolve) => setTimeout(resolve, 20000))
__dirname, }
'./.next/static/', prom.then(() => {
decodeURI(pathname.slice('/_next/static/'.length)) res.write(
), fs.readFileSync(
'utf8' path.join(
__dirname,
'./.next/static/',
decodeURI(pathname.slice('/_next/static/'.length))
),
'utf8'
)
) )
) return res.end()
return res.end() })
} else { } else {
if (pathname === '') {
pathname = '/index'
}
const ext = isDataReq ? 'json' : 'html' const ext = isDataReq ? 'json' : 'html'
if ( if (
fs.existsSync( fs.existsSync(
......
...@@ -10,7 +10,9 @@ import { ...@@ -10,7 +10,9 @@ import {
nextBuild, nextBuild,
renderViaHTTP, renderViaHTTP,
initNextServerScript, initNextServerScript,
waitFor,
} from 'next-test-utils' } from 'next-test-utils'
import webdriver from 'next-webdriver'
jest.setTimeout(1000 * 60 * 2) jest.setTimeout(1000 * 60 * 2)
...@@ -33,7 +35,7 @@ const startServerlessEmulator = async (dir, port) => { ...@@ -33,7 +35,7 @@ const startServerlessEmulator = async (dir, port) => {
{ ...process.env }, { ...process.env },
{ PORT: port, BUILD_ID: await getBuildId(dir) } { PORT: port, BUILD_ID: await getBuildId(dir) }
) )
return initNextServerScript(scriptPath, /ready on/i, env) return initNextServerScript(scriptPath, /ready on/i, env, false, {})
} }
describe('Font Optimization', () => { describe('Font Optimization', () => {
...@@ -122,38 +124,70 @@ describe('Font Optimization', () => { ...@@ -122,38 +124,70 @@ describe('Font Optimization', () => {
it(`should inline the ${property} fonts for static pages`, async () => { it(`should inline the ${property} fonts for static pages`, async () => {
const html = await renderViaHTTP(appPort, '/index') const html = await renderViaHTTP(appPort, '/index')
const $ = cheerio.load(html)
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true) expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(html).toContain( expect(
`<link rel="stylesheet" data-href="${staticFont}"/>` $(`link[rel=stylesheet][data-href="${staticFont}"]`).length
) ).toBe(1)
expect(html).toMatch(staticPattern) expect(html).toMatch(staticPattern)
}) })
it(`should inline the ${property} fonts for static pages with Next/Head`, async () => { it(`should inline the ${property} fonts for static pages with Next/Head`, async () => {
const html = await renderViaHTTP(appPort, '/static-head') const html = await renderViaHTTP(appPort, '/static-head')
const $ = cheerio.load(html)
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true) expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(html).toContain( expect(
`<link rel="stylesheet" data-href="${staticHeadFont}"/>` $(`link[rel=stylesheet][data-href="${staticHeadFont}"]`).length
) ).toBe(1)
expect(html).toMatch(staticHeadPattern) expect(html).toMatch(staticHeadPattern)
}) })
it(`should inline the ${property} fonts for SSR pages`, async () => { it(`should inline the ${property} fonts for SSR pages`, async () => {
const html = await renderViaHTTP(appPort, '/stars') const html = await renderViaHTTP(appPort, '/stars')
const $ = cheerio.load(html)
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true) expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(html).toContain( expect(
`<link rel="stylesheet" data-href="${starsFont}"/>` $(`link[rel=stylesheet][data-href="${starsFont}"]`).length
) ).toBe(1)
expect(html).toMatch(starsPattern) expect(html).toMatch(starsPattern)
}) })
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)
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true) expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(html).toContain(`<link rel="stylesheet" href="${staticFont}">`) expect($(`link[rel=stylesheet][href="${staticFont}"]`).length).toBe(1)
expect(html).not.toMatch(staticPattern) expect(html).not.toMatch(staticPattern)
}) })
it('should work for fonts loaded on navigation', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await waitFor(1000)
const baseFont = await browser.elementByCss(
`style[data-href="${staticFont}"]`
)
expect(baseFont).toBeDefined()
await browser.waitForElementByCss('#with-font')
await browser.click('#with-font')
await browser.waitForElementByCss('#with-font-container')
const pageFontCss = await browser.elementsByCss(
`style[data-href="${withFont}"]`
)
expect(pageFontCss.length).toBe(0)
const pageFont = await browser.elementByCss(
`link[href="${withFont}"]`
)
expect(pageFont).toBeDefined()
} finally {
if (browser) await browser.close()
}
})
it('should minify the css', async () => { it('should minify the css', async () => {
const snapshotJson = JSON.parse( const snapshotJson = JSON.parse(
await fs.readFile(join(appDir, 'manifest-snapshot.json'), { await fs.readFile(join(appDir, 'manifest-snapshot.json'), {
...@@ -225,12 +259,13 @@ describe('Font Optimization', () => { ...@@ -225,12 +259,13 @@ describe('Font Optimization', () => {
) )
await nextBuild(appDir) await nextBuild(appDir)
appPort = await findPort() appPort = await findPort()
await startServerlessEmulator(appDir, appPort) app = await startServerlessEmulator(appDir, appPort)
builtServerPagesDir = join(appDir, '.next', 'serverless') builtServerPagesDir = join(appDir, '.next', 'serverless')
builtPage = (file) => join(builtServerPagesDir, file) builtPage = (file) => join(builtServerPagesDir, file)
}) })
afterAll(async () => { afterAll(async () => {
await fs.remove(nextConfig) await fs.remove(nextConfig)
await killApp(app)
}) })
runTests() runTests()
}) })
......
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