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