Unverified Commit 6895f9b0 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Replace <link rel=stylesheet> client-side transitions with <style> tags (#16581)

This pull request replaces our client-side style transitions with `<style>` tags over async `<link rel=stylesheet>` tags. This should fix some edge cases users see with Chrome accidentally causing a FOUC.

This also removes the need to perform an async operation before starting the render, which should remove any perceivable navigation delay.

---

Fixes #16289
parent 990c1792
This diff is collapsed.
......@@ -33,6 +33,7 @@ const relPrefetch =
'prefetch'
const relPreload = hasRel('preload') ? 'preload' : relPrefetch
const relPreloadStyle = 'fetch'
const hasNoModule = 'noModule' in document.createElement('script')
......@@ -51,33 +52,27 @@ function normalizeRoute(route: string) {
return route.replace(/\/$/, '')
}
export function createLink(
function appendLink(
href: string,
rel: string,
as?: string,
link?: HTMLLinkElement
): [HTMLLinkElement, Promise<any>] {
link = document.createElement('link')
return [
link,
new Promise((res, rej) => {
// The order of property assignment here is intentional:
if (as) link!.as = as
link!.rel = rel
link!.crossOrigin = process.env.__NEXT_CROSS_ORIGIN!
link!.onload = res
link!.onerror = rej
// `href` should always be last:
link!.href = href
}),
]
}
): Promise<any> {
return new Promise((res, rej) => {
link = document.createElement('link')
// The order of property assignment here is intentional:
if (as) link!.as = as
link!.rel = rel
link!.crossOrigin = process.env.__NEXT_CROSS_ORIGIN!
link!.onload = res
link!.onerror = rej
// `href` should always be last:
link!.href = href
function appendLink(href: string, rel: string, as?: string): Promise<any> {
const [link, res] = createLink(href, rel, as)
document.head.appendChild(link)
return res
document.head.appendChild(link)
})
}
function loadScript(url: string): Promise<any> {
......@@ -94,16 +89,17 @@ function loadScript(url: string): Promise<any> {
})
}
export type StyleSheetTuple = { href: string; text: string }
export type GoodPageCache = {
page: ComponentType
mod: any
styleSheets: string[]
styleSheets: StyleSheetTuple[]
}
export type PageCacheEntry = { error: any } | GoodPageCache
export default class PageLoader {
private initialPage: string
private initialStyleSheets: string[]
private initialStyleSheets: StyleSheetTuple[]
private buildId: string
private assetPrefix: string
private pageCache: Record<string, PageCacheEntry>
......@@ -117,7 +113,7 @@ export default class PageLoader {
buildId: string,
assetPrefix: string,
initialPage: string,
initialStyleSheets: string[]
initialStyleSheets: StyleSheetTuple[]
) {
this.initialPage = initialPage
this.initialStyleSheets = initialStyleSheets
......@@ -348,7 +344,7 @@ export default class PageLoader {
// 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, 'style').catch(() => {
appendLink(d, relPreload, relPreloadStyle).catch(() => {
/* ignore preload error */
})
}
......@@ -381,7 +377,7 @@ export default class PageLoader {
// This method if called by the route code.
registerPage(route: string, regFn: () => any) {
const register = (styleSheets: string[]) => {
const register = (styleSheets: StyleSheetTuple[]) => {
try {
const mod = regFn()
const pageData: PageCacheEntry = {
......@@ -419,7 +415,14 @@ export default class PageLoader {
}
}
const promisedDeps: Promise<string[]> =
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 promisedDeps: Promise<StyleSheetTuple[]> =
// Shared styles will already be on the page:
route === '/_app' ||
// We use `style-loader` in development:
......@@ -430,8 +433,14 @@ export default class PageLoader {
: // Tests that this does not block hydration:
// test/integration/css-fixtures/hydrate-without-deps/
this.getDependencies(route)
.then((deps) => deps.filter((d) => d.endsWith('.css')))
.then((cssFiles) =>
// These files should've already been fetched by now, so this
// should resolve pretty much instantly.
Promise.all(cssFiles.map((d) => fetchStyleSheet(d)))
)
promisedDeps.then(
(deps) => register(deps.filter((d) => d.endsWith('.css'))),
(deps) => register(deps),
(error) => {
this.pageCache[route] = { error }
this.pageRegisterEvents.emit(route, { error })
......@@ -478,7 +487,7 @@ export default class PageLoader {
appendLink(
url,
relPrefetch,
url.endsWith('.css') ? 'style' : 'script'
url.endsWith('.css') ? relPreloadStyle : 'script'
),
process.env.NODE_ENV === 'production' &&
!isDependency &&
......
......@@ -7,7 +7,7 @@ import {
normalizePathTrailingSlash,
removePathTrailingSlash,
} from '../../../client/normalize-trailing-slash'
import { GoodPageCache } from '../../../client/page-loader'
import { GoodPageCache, StyleSheetTuple } from '../../../client/page-loader'
import { denormalizePagePath } from '../../server/denormalize-page-path'
import mitt, { MittEmitter } from '../mitt'
import {
......@@ -159,7 +159,7 @@ export type PrefetchOptions = {
export type PrivateRouteInfo = {
Component: ComponentType
styleSheets: string[]
styleSheets: StyleSheetTuple[]
__N_SSG?: boolean
__N_SSP?: boolean
props?: Record<string, any>
......@@ -268,7 +268,7 @@ export default class Router implements BaseRouter {
initialProps: any
pageLoader: any
Component: ComponentType
initialStyleSheets: string[]
initialStyleSheets: StyleSheetTuple[]
App: AppComponent
wrapApp: (App: AppComponent) => any
err?: Error
......
......@@ -504,6 +504,7 @@ export class Head extends Component<
{process.env.__NEXT_OPTIMIZE_FONTS
? this.makeStylesheetInert(this.getCssLinks(files))
: this.getCssLinks(files)}
<noscript data-n-css />
{!disableRuntimeJS && this.getPreloadDynamicChunks()}
{!disableRuntimeJS && this.getPreloadMainLinks(files)}
{this.context.isDevelopment && (
......
......@@ -88,7 +88,7 @@ describe('CSS Module client-side navigation in Production', () => {
// Check that Red was preloaded
const result = await browser.eval(
`[].slice.call(document.querySelectorAll('link[rel="prefetch"][as="style"]')).map(e=>({href:e.href})).sort()`
`[].slice.call(document.querySelectorAll('link[rel="prefetch"][as="fetch"]')).map(e=>({href:e.href})).sort()`
)
expect(result.length).toBe(1)
......@@ -96,11 +96,13 @@ describe('CSS Module client-side navigation in Production', () => {
const cssPreloads = await browser.eval(
`[].slice.call(document.querySelectorAll('link[rel=preload][href*=".css"]')).map(e=>e.as)`
)
expect(cssPreloads.every((e) => e === 'style')).toBe(true)
expect(cssPreloads.every((e) => e === 'style' || e === 'fetch')).toBe(
true
)
const cssPreloads2 = await browser.eval(
`[].slice.call(document.querySelectorAll('link[rel=prefetch][href*=".css"]')).map(e=>e.as)`
)
expect(cssPreloads2.every((e) => e === 'style')).toBe(true)
expect(cssPreloads2.every((e) => e === 'fetch')).toBe(true)
await browser.elementByCss('#link-red').click()
......@@ -245,7 +247,7 @@ describe.skip('CSS Module client-side navigation in Production (Modern)', () =>
// Check that Red was preloaded
const result = await browser.eval(
`[].slice.call(document.querySelectorAll('link[rel="prefetch"][as="style"]')).map(e=>({href:e.href})).sort()`
`[].slice.call(document.querySelectorAll('link[rel="prefetch"][as="fetch"]')).map(e=>({href:e.href})).sort()`
)
expect(result.length).toBe(1)
......@@ -253,11 +255,13 @@ describe.skip('CSS Module client-side navigation in Production (Modern)', () =>
const cssPreloads = await browser.eval(
`[].slice.call(document.querySelectorAll('link[rel=preload][href*=".css"]')).map(e=>e.as)`
)
expect(cssPreloads.every((e) => e === 'style')).toBe(true)
expect(cssPreloads.every((e) => e === 'style' || e === 'fetch')).toBe(
true
)
const cssPreloads2 = await browser.eval(
`[].slice.call(document.querySelectorAll('link[rel=prefetch][href*=".css"]')).map(e=>e.as)`
)
expect(cssPreloads2.every((e) => e === 'style')).toBe(true)
expect(cssPreloads2.every((e) => e === 'fetch')).toBe(true)
await browser.elementByCss('#link-red').click()
......
......@@ -1133,15 +1133,29 @@ describe('CSS Support', () => {
await browser.waitForElementByCss('#link-other').click()
await checkRedTitle(browser)
const newPrevSiblingHref = await browser.eval(
`document.querySelector('link[rel=stylesheet][data-n-p]').previousSibling.getAttribute('href')`
const newPrevSibling = await browser.eval(
`document.querySelector('style[data-n-href]').previousSibling.getAttribute('data-n-css')`
)
const newPageHref = await browser.eval(
`document.querySelector('link[rel=stylesheet][data-n-p]').getAttribute('href')`
`document.querySelector('style[data-n-href]').getAttribute('data-n-href')`
)
expect(newPrevSibling).toBeTruthy()
expect(newPageHref).toBeDefined()
expect(newPrevSiblingHref).toBe(prevSiblingHref)
expect(newPageHref).not.toBe(currentPageHref)
// Navigate to home:
await browser.waitForElementByCss('#link-index').click()
await checkBlackTitle(browser)
const newPrevSibling2 = await browser.eval(
`document.querySelector('style[data-n-href]').previousSibling.getAttribute('data-n-css')`
)
const newPageHref2 = await browser.eval(
`document.querySelector('style[data-n-href]').getAttribute('data-n-href')`
)
expect(newPrevSibling2).toBeTruthy()
expect(newPageHref2).toBeDefined()
expect(newPageHref2).toBe(currentPageHref)
} finally {
await browser.close()
}
......
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