Unverified Commit e9054744 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Load CSS early instead of only preloading (#18846)

While we were fixing how Next.js handled CSS, we added a complex prefetch, preload, fetch sequence to acquire the CSS asset.

This unnecessarily overcomplicated what could've been only a `fetch()` from the very start!

---

Fixes #16932
parent ac54573b
...@@ -38,9 +38,6 @@ const relPrefetch = ...@@ -38,9 +38,6 @@ const relPrefetch =
// IE 11, Edge 12+, nearly all evergreen // IE 11, Edge 12+, nearly all evergreen
'prefetch' 'prefetch'
const relPreload = hasRel('preload') ? 'preload' : relPrefetch
const relPreloadStyle = 'fetch'
const hasNoModule = 'noModule' in document.createElement('script') const hasNoModule = 'noModule' in document.createElement('script')
function normalizeRoute(route: string) { function normalizeRoute(route: string) {
...@@ -102,6 +99,7 @@ export default class PageLoader { ...@@ -102,6 +99,7 @@ export default class PageLoader {
private buildId: string private buildId: string
private assetPrefix: string private assetPrefix: string
private pageCache: Record<string, PageCacheEntry> private pageCache: Record<string, PageCacheEntry>
private cssc: Record<string, Promise<string>>
private pageRegisterEvents: MittEmitter private pageRegisterEvents: MittEmitter
private loadingRoutes: Record<string, boolean> private loadingRoutes: Record<string, boolean>
private promisedBuildManifest?: Promise<ClientBuildManifest> private promisedBuildManifest?: Promise<ClientBuildManifest>
...@@ -115,6 +113,7 @@ export default class PageLoader { ...@@ -115,6 +113,7 @@ export default class PageLoader {
this.assetPrefix = assetPrefix this.assetPrefix = assetPrefix
this.pageCache = {} this.pageCache = {}
this.cssc = {}
this.pageRegisterEvents = mitt() this.pageRegisterEvents = mitt()
this.loadingRoutes = { this.loadingRoutes = {
// By default these 2 pages are being loaded in the initial html // By default these 2 pages are being loaded in the initial html
...@@ -175,6 +174,16 @@ export default class PageLoader { ...@@ -175,6 +174,16 @@ export default class PageLoader {
} }
} }
private fetchStyleSheet(href: string): Promise<StyleSheetTuple> {
if (!this.cssc[href]) {
this.cssc[href] = fetch(href).then((res) => {
if (!res.ok) throw pageLoadError(href)
return res.text()
})
}
return this.cssc[href].then((text) => ({ href, text }))
}
// Returns a promise for the dependencies for a particular route // Returns a promise for the dependencies for a particular route
private getDependencies(route: string): Promise<string[]> { private getDependencies(route: string): Promise<string[]> {
return this.promisedBuildManifest!.then((m) => { return this.promisedBuildManifest!.then((m) => {
...@@ -268,25 +277,8 @@ export default class PageLoader { ...@@ -268,25 +277,8 @@ export default class PageLoader {
) { ) {
pending.push(loadScript(d)) pending.push(loadScript(d))
} }
if (d.endsWith('.css')) {
// Prefetch CSS as it'll be needed when the page JavaScript pending.push(this.fetchStyleSheet(d))
// evaluates. This will only trigger if explicit prefetching is
// disabled for a <Link>... prefetching in this case is desirable
// because we *know* it's going to be used very soon (page was
// loaded).
if (
d.endsWith('.css') &&
!document.querySelector(
`link[rel="${relPreload}"][href^="${d}"]`
)
) {
// This is not pushed into `pending` because we don't need to
// wait for these to resolve. To prevent an unhandled
// rejection, we swallow the error which is handled later in
// the rendering cycle (this is just a preload optimization).
appendLink(d, relPreload, relPreloadStyle).catch(() => {
/* ignore preload error */
})
} }
}) })
return Promise.all(pending) return Promise.all(pending)
...@@ -355,13 +347,6 @@ export default class PageLoader { ...@@ -355,13 +347,6 @@ export default class PageLoader {
} }
} }
function fetchStyleSheet(href: string): Promise<StyleSheetTuple> {
return fetch(href).then((res) => {
if (!res.ok) throw pageLoadError(href)
return res.text().then((text) => ({ href, text }))
})
}
const isInitialLoad = route === this.initialPage const isInitialLoad = route === this.initialPage
const promisedDeps: Promise<StyleSheetTuple[]> = const promisedDeps: Promise<StyleSheetTuple[]> =
// Shared styles will already be on the page: // Shared styles will already be on the page:
...@@ -383,7 +368,7 @@ export default class PageLoader { ...@@ -383,7 +368,7 @@ export default class PageLoader {
).then((cssFiles) => ).then((cssFiles) =>
// These files should've already been fetched by now, so this // These files should've already been fetched by now, so this
// should resolve instantly. // should resolve instantly.
Promise.all(cssFiles.map((d) => fetchStyleSheet(d))).catch( Promise.all(cssFiles.map((d) => this.fetchStyleSheet(d))).catch(
(err) => { (err) => {
if (isInitialLoad) { if (isInitialLoad) {
Object.defineProperty(err, INITIAL_CSS_LOAD_ERROR, {}) Object.defineProperty(err, INITIAL_CSS_LOAD_ERROR, {})
...@@ -432,27 +417,22 @@ export default class PageLoader { ...@@ -432,27 +417,22 @@ export default class PageLoader {
} }
} }
return Promise.all( return Promise.all([
document.querySelector(`link[rel="${relPrefetch}"][href^="${url}"]`) url
? [] ? url.endsWith('.css')
: [ ? this.fetchStyleSheet(url)
url && : !document.querySelector(
appendLink( `link[rel="${relPrefetch}"][href^="${url}"]`
url, ) && appendLink(url, relPrefetch, 'script')
relPrefetch, : 0,
url.endsWith('.css') ? relPreloadStyle : 'script' process.env.NODE_ENV === 'production' &&
), !isDependency &&
process.env.NODE_ENV === 'production' && this.getDependencies(route).then((urls) =>
!isDependency && Promise.all(
this.getDependencies(route).then((urls) => urls.map((dependencyUrl) => this.prefetch(dependencyUrl, true))
Promise.all( )
urls.map((dependencyUrl) => ),
this.prefetch(dependencyUrl, true) ]).then(
)
)
),
]
).then(
// do not return any data // do not return any data
() => {}, () => {},
// swallow prefetch errors // swallow prefetch errors
......
/* eslint-env jest */ /* eslint-env jest */
import { join } from 'path' import cheerio from 'cheerio'
import { remove } from 'fs-extra' import { remove } from 'fs-extra'
import { import {
nextBuild, check,
nextStart,
findPort, findPort,
killApp, killApp,
nextBuild,
nextStart,
renderViaHTTP, renderViaHTTP,
} from 'next-test-utils' } from 'next-test-utils'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { join } from 'path'
jest.setTimeout(1000 * 60 * 1) jest.setTimeout(1000 * 60 * 1)
...@@ -86,11 +87,19 @@ describe('CSS Module client-side navigation in Production', () => { ...@@ -86,11 +87,19 @@ describe('CSS Module client-side navigation in Production', () => {
) )
expect(redColor).toMatchInlineSnapshot(`"rgb(0, 0, 255)"`) expect(redColor).toMatchInlineSnapshot(`"rgb(0, 0, 255)"`)
// Check that Red was preloaded await check(
const result = await browser.eval( async () => {
`[].slice.call(document.querySelectorAll('link[rel="prefetch"][as="fetch"]')).map(e=>({href:e.href})).sort()` // Check that Red was preloaded
const result = await browser.eval(
`Promise.all(Object.entries(window.next.router.pageLoader.cssc).map(v=>v[1]))`
)
expect(result.length).toBe(2)
expect(result).toContainEqual(expect.stringContaining('color:red'))
return 'yes'
},
/yes/,
true
) )
expect(result.length).toBe(1)
// Check that CSS was not loaded as script // Check that CSS was not loaded as script
const cssPreloads = await browser.eval( const cssPreloads = await browser.eval(
......
...@@ -4,7 +4,7 @@ import css from './index.module.css' ...@@ -4,7 +4,7 @@ import css from './index.module.css'
export default function Home() { export default function Home() {
return ( return (
<main> <main>
<Link href="/other"> <Link href="/other" prefetch={false}>
<a id="link-other">other</a> <a id="link-other">other</a>
</Link> </Link>
<br /> <br />
......
...@@ -1104,7 +1104,7 @@ describe('CSS Support', () => { ...@@ -1104,7 +1104,7 @@ describe('CSS Support', () => {
async function checkCssPreloadCount(browser) { async function checkCssPreloadCount(browser) {
return Number( return Number(
await browser.eval( await browser.eval(
` [].slice.call(document.querySelectorAll('link[rel=preload][href$="css"]')).length` `Object.keys(window.next.router.pageLoader.cssc).length`
) )
) )
} }
......
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