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

Improving script loading strategy (#24939)

parent 1cb83c1b
...@@ -1260,6 +1260,7 @@ export default async function getBaseWebpackConfig( ...@@ -1260,6 +1260,7 @@ export default async function getBaseWebpackConfig(
pageEnv: config.experimental.pageEnv, pageEnv: config.experimental.pageEnv,
excludeDefaultMomentLocales: config.future.excludeDefaultMomentLocales, excludeDefaultMomentLocales: config.future.excludeDefaultMomentLocales,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
disableOptimizedLoading: config.experimental.disableOptimizedLoading,
target, target,
reactProductionProfiling, reactProductionProfiling,
webpack: !!config.webpack, webpack: !!config.webpack,
......
...@@ -369,6 +369,7 @@ export default async function exportApp( ...@@ -369,6 +369,7 @@ export default async function exportApp(
defaultLocale: i18n?.defaultLocale, defaultLocale: i18n?.defaultLocale,
domainLocales: i18n?.domains, domainLocales: i18n?.domains,
trailingSlash: nextConfig.trailingSlash, trailingSlash: nextConfig.trailingSlash,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
} }
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
...@@ -541,6 +542,8 @@ export default async function exportApp( ...@@ -541,6 +542,8 @@ export default async function exportApp(
optimizeFonts: nextConfig.optimizeFonts, optimizeFonts: nextConfig.optimizeFonts,
optimizeImages: nextConfig.experimental.optimizeImages, optimizeImages: nextConfig.experimental.optimizeImages,
optimizeCss: nextConfig.experimental.optimizeCss, optimizeCss: nextConfig.experimental.optimizeCss,
disableOptimizedLoading:
nextConfig.experimental.disableOptimizedLoading,
parentSpanId: pageExportSpan.id, parentSpanId: pageExportSpan.id,
}) })
......
...@@ -52,6 +52,7 @@ interface ExportPageInput { ...@@ -52,6 +52,7 @@ interface ExportPageInput {
optimizeFonts: boolean optimizeFonts: boolean
optimizeImages?: boolean optimizeImages?: boolean
optimizeCss: any optimizeCss: any
disableOptimizedLoading: any
parentSpanId: any parentSpanId: any
} }
...@@ -70,6 +71,7 @@ interface RenderOpts { ...@@ -70,6 +71,7 @@ interface RenderOpts {
ampSkipValidation?: boolean ampSkipValidation?: boolean
optimizeFonts?: boolean optimizeFonts?: boolean
optimizeImages?: boolean optimizeImages?: boolean
disableOptimizedLoading?: boolean
optimizeCss?: any optimizeCss?: any
fontManifest?: FontManifest fontManifest?: FontManifest
locales?: string[] locales?: string[]
...@@ -98,6 +100,7 @@ export default async function exportPage({ ...@@ -98,6 +100,7 @@ export default async function exportPage({
optimizeFonts, optimizeFonts,
optimizeImages, optimizeImages,
optimizeCss, optimizeCss,
disableOptimizedLoading,
}: ExportPageInput): Promise<ExportPageResults> { }: ExportPageInput): Promise<ExportPageResults> {
const exportPageSpan = trace('export-page-worker', parentSpanId) const exportPageSpan = trace('export-page-worker', parentSpanId)
...@@ -284,6 +287,7 @@ export default async function exportPage({ ...@@ -284,6 +287,7 @@ export default async function exportPage({
optimizeImages, optimizeImages,
/// @ts-ignore /// @ts-ignore
optimizeCss, optimizeCss,
disableOptimizedLoading,
distDir, distDir,
fontManifest: optimizeFonts fontManifest: optimizeFonts
? requireFontManifest(distDir, serverless) ? requireFontManifest(distDir, serverless)
...@@ -357,6 +361,7 @@ export default async function exportPage({ ...@@ -357,6 +361,7 @@ export default async function exportPage({
optimizeFonts, optimizeFonts,
optimizeImages, optimizeImages,
optimizeCss, optimizeCss,
disableOptimizedLoading,
fontManifest: optimizeFonts fontManifest: optimizeFonts
? requireFontManifest(distDir, serverless) ? requireFontManifest(distDir, serverless)
: null, : null,
......
...@@ -193,6 +193,7 @@ export type DocumentProps = DocumentInitialProps & { ...@@ -193,6 +193,7 @@ export type DocumentProps = DocumentInitialProps & {
devOnlyCacheBusterQueryString: string devOnlyCacheBusterQueryString: string
scriptLoader: { afterInteractive?: string[]; beforeInteractive?: any[] } scriptLoader: { afterInteractive?: string[]; beforeInteractive?: any[] }
locale?: string locale?: string
disableOptimizedLoading?: boolean
} }
/** /**
......
...@@ -61,6 +61,7 @@ export type NextConfig = { [key: string]: any } & { ...@@ -61,6 +61,7 @@ export type NextConfig = { [key: string]: any } & {
eslint?: boolean eslint?: boolean
reactRoot: boolean reactRoot: boolean
enableBlurryPlaceholder: boolean enableBlurryPlaceholder: boolean
disableOptimizedLoading: boolean
} }
} }
...@@ -118,6 +119,7 @@ export const defaultConfig: NextConfig = { ...@@ -118,6 +119,7 @@ export const defaultConfig: NextConfig = {
eslint: false, eslint: false,
reactRoot: Number(process.env.NEXT_PRIVATE_REACT_ROOT) > 0, reactRoot: Number(process.env.NEXT_PRIVATE_REACT_ROOT) > 0,
enableBlurryPlaceholder: false, enableBlurryPlaceholder: false,
disableOptimizedLoading: true,
}, },
future: { future: {
strictPostcssConfiguration: false, strictPostcssConfiguration: false,
......
...@@ -157,6 +157,7 @@ export default class Server { ...@@ -157,6 +157,7 @@ export default class Server {
images: string images: string
fontManifest: FontManifest fontManifest: FontManifest
optimizeImages: boolean optimizeImages: boolean
disableOptimizedLoading: boolean
optimizeCss: any optimizeCss: any
locale?: string locale?: string
locales?: string[] locales?: string[]
...@@ -217,6 +218,8 @@ export default class Server { ...@@ -217,6 +218,8 @@ export default class Server {
: null, : null,
optimizeImages: !!this.nextConfig.experimental.optimizeImages, optimizeImages: !!this.nextConfig.experimental.optimizeImages,
optimizeCss: this.nextConfig.experimental.optimizeCss, optimizeCss: this.nextConfig.experimental.optimizeCss,
disableOptimizedLoading: this.nextConfig.experimental
.disableOptimizedLoading,
domainLocales: this.nextConfig.i18n?.domains, domainLocales: this.nextConfig.i18n?.domains,
distDir: this.distDir, distDir: this.distDir,
} }
......
...@@ -190,6 +190,7 @@ export type RenderOptsPartial = { ...@@ -190,6 +190,7 @@ export type RenderOptsPartial = {
locales?: string[] locales?: string[]
defaultLocale?: string defaultLocale?: string
domainLocales?: DomainLocales domainLocales?: DomainLocales
disableOptimizedLoading?: boolean
} }
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
...@@ -234,6 +235,7 @@ function renderDocument( ...@@ -234,6 +235,7 @@ function renderDocument(
defaultLocale, defaultLocale,
domainLocales, domainLocales,
isPreview, isPreview,
disableOptimizedLoading,
}: RenderOpts & { }: RenderOpts & {
props: any props: any
docComponentsRendered: DocumentProps['docComponentsRendered'] docComponentsRendered: DocumentProps['docComponentsRendered']
...@@ -305,6 +307,7 @@ function renderDocument( ...@@ -305,6 +307,7 @@ function renderDocument(
devOnlyCacheBusterQueryString, devOnlyCacheBusterQueryString,
scriptLoader, scriptLoader,
locale, locale,
disableOptimizedLoading,
...docProps, ...docProps,
})} })}
</AmpStateContext.Provider> </AmpStateContext.Provider>
......
...@@ -51,6 +51,115 @@ function getDocumentFiles( ...@@ -51,6 +51,115 @@ function getDocumentFiles(
} }
} }
function getPolyfillScripts(context: DocumentProps, props: OriginProps) {
// polyfills.js has to be rendered as nomodule without async
// It also has to be the first script to load
const {
assetPrefix,
buildManifest,
devOnlyCacheBusterQueryString,
disableOptimizedLoading,
} = context
return buildManifest.polyfillFiles
.filter(
(polyfill) => polyfill.endsWith('.js') && !polyfill.endsWith('.module.js')
)
.map((polyfill) => (
<script
key={polyfill}
defer={!disableOptimizedLoading}
nonce={props.nonce}
crossOrigin={props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN}
noModule={true}
src={`${assetPrefix}/_next/${polyfill}${devOnlyCacheBusterQueryString}`}
/>
))
}
function getPreNextScripts(context: DocumentProps, props: OriginProps) {
const { scriptLoader, disableOptimizedLoading } = context
return (scriptLoader.beforeInteractive || []).map(
(file: ScriptLoaderProps) => {
const { strategy, ...scriptProps } = file
return (
<script
{...scriptProps}
defer={!disableOptimizedLoading}
nonce={props.nonce}
crossOrigin={props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN}
/>
)
}
)
}
function getDynamicChunks(
context: DocumentProps,
props: OriginProps,
files: DocumentFiles
) {
const {
dynamicImports,
assetPrefix,
isDevelopment,
devOnlyCacheBusterQueryString,
disableOptimizedLoading,
} = context
return dynamicImports.map((file) => {
if (!file.endsWith('.js') || files.allFiles.includes(file)) return null
return (
<script
async={!isDevelopment && disableOptimizedLoading}
defer={!disableOptimizedLoading}
key={file}
src={`${assetPrefix}/_next/${encodeURI(
file
)}${devOnlyCacheBusterQueryString}`}
nonce={props.nonce}
crossOrigin={props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN}
/>
)
})
}
function getScripts(
context: DocumentProps,
props: OriginProps,
files: DocumentFiles
) {
const {
assetPrefix,
buildManifest,
isDevelopment,
devOnlyCacheBusterQueryString,
disableOptimizedLoading,
} = context
const normalScripts = files.allFiles.filter((file) => file.endsWith('.js'))
const lowPriorityScripts = buildManifest.lowPriorityFiles?.filter((file) =>
file.endsWith('.js')
)
return [...normalScripts, ...lowPriorityScripts].map((file) => {
return (
<script
key={file}
src={`${assetPrefix}/_next/${encodeURI(
file
)}${devOnlyCacheBusterQueryString}`}
nonce={props.nonce}
async={!isDevelopment && disableOptimizedLoading}
defer={!disableOptimizedLoading}
crossOrigin={props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN}
/>
)
})
}
/** /**
* `Document` component handles the initial `document` markup and renders only on the server side. * `Document` component handles the initial `document` markup and renders only on the server side.
* Commonly used for implementing server side rendering for `css-in-js` libraries. * Commonly used for implementing server side rendering for `css-in-js` libraries.
...@@ -285,6 +394,22 @@ export class Head extends Component< ...@@ -285,6 +394,22 @@ export class Head extends Component<
] ]
} }
getDynamicChunks(files: DocumentFiles) {
return getDynamicChunks(this.context, this.props, files)
}
getPreNextScripts() {
return getPreNextScripts(this.context, this.props)
}
getScripts(files: DocumentFiles) {
return getScripts(this.context, this.props, files)
}
getPolyfillScripts() {
return getPolyfillScripts(this.context, this.props)
}
handleDocumentScriptLoaderItems(children: React.ReactNode): ReactNode[] { handleDocumentScriptLoaderItems(children: React.ReactNode): ReactNode[] {
const { scriptLoader } = this.context const { scriptLoader } = this.context
const scriptLoaderItems: ScriptLoaderProps[] = [] const scriptLoaderItems: ScriptLoaderProps[] = []
...@@ -347,9 +472,12 @@ export class Head extends Component< ...@@ -347,9 +472,12 @@ export class Head extends Component<
headTags, headTags,
unstable_runtimeJS, unstable_runtimeJS,
unstable_JsPreload, unstable_JsPreload,
disableOptimizedLoading,
} = this.context } = this.context
const disableRuntimeJS = unstable_runtimeJS === false const disableRuntimeJS = unstable_runtimeJS === false
const disableJsPreload = unstable_JsPreload === false const disableJsPreload =
unstable_JsPreload === false || !disableOptimizedLoading
this.context.docComponentsRendered.Head = true this.context.docComponentsRendered.Head = true
...@@ -582,6 +710,18 @@ export class Head extends Component< ...@@ -582,6 +710,18 @@ export class Head extends Component<
{!disableRuntimeJS && {!disableRuntimeJS &&
!disableJsPreload && !disableJsPreload &&
this.getPreloadMainLinks(files)} this.getPreloadMainLinks(files)}
{!disableOptimizedLoading &&
!disableRuntimeJS &&
this.getPolyfillScripts()}
{!disableOptimizedLoading &&
!disableRuntimeJS &&
this.getPreNextScripts()}
{!disableOptimizedLoading &&
!disableRuntimeJS &&
this.getDynamicChunks(files)}
{!disableOptimizedLoading &&
!disableRuntimeJS &&
this.getScripts(files)}
{process.env.__NEXT_OPTIMIZE_CSS && this.getCssLinks(files)} {process.env.__NEXT_OPTIMIZE_CSS && this.getCssLinks(files)}
{process.env.__NEXT_OPTIMIZE_CSS && ( {process.env.__NEXT_OPTIMIZE_CSS && (
<noscript data-n-css={this.props.nonce ?? ''} /> <noscript data-n-css={this.props.nonce ?? ''} />
...@@ -627,106 +767,19 @@ export class NextScript extends Component<OriginProps> { ...@@ -627,106 +767,19 @@ export class NextScript extends Component<OriginProps> {
'!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();' '!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();'
getDynamicChunks(files: DocumentFiles) { getDynamicChunks(files: DocumentFiles) {
const { return getDynamicChunks(this.context, this.props, files)
dynamicImports,
assetPrefix,
isDevelopment,
devOnlyCacheBusterQueryString,
} = this.context
return dynamicImports.map((file) => {
if (!file.endsWith('.js') || files.allFiles.includes(file)) return null
return (
<script
async={!isDevelopment}
key={file}
src={`${assetPrefix}/_next/${encodeURI(
file
)}${devOnlyCacheBusterQueryString}`}
nonce={this.props.nonce}
crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
}
/>
)
})
} }
getPreNextScripts() { getPreNextScripts() {
const { scriptLoader } = this.context return getPreNextScripts(this.context, this.props)
return (scriptLoader.beforeInteractive || []).map(
(file: ScriptLoaderProps) => {
const { strategy, ...props } = file
return (
<script
{...props}
nonce={this.props.nonce}
crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
}
/>
)
}
)
} }
getScripts(files: DocumentFiles) { getScripts(files: DocumentFiles) {
const { return getScripts(this.context, this.props, files)
assetPrefix,
buildManifest,
isDevelopment,
devOnlyCacheBusterQueryString,
} = this.context
const normalScripts = files.allFiles.filter((file) => file.endsWith('.js'))
const lowPriorityScripts = buildManifest.lowPriorityFiles?.filter((file) =>
file.endsWith('.js')
)
return [...normalScripts, ...lowPriorityScripts].map((file) => {
return (
<script
key={file}
src={`${assetPrefix}/_next/${encodeURI(
file
)}${devOnlyCacheBusterQueryString}`}
nonce={this.props.nonce}
async={!isDevelopment}
crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
}
/>
)
})
} }
getPolyfillScripts() { getPolyfillScripts() {
// polyfills.js has to be rendered as nomodule without async return getPolyfillScripts(this.context, this.props)
// It also has to be the first script to load
const {
assetPrefix,
buildManifest,
devOnlyCacheBusterQueryString,
} = this.context
return buildManifest.polyfillFiles
.filter(
(polyfill) =>
polyfill.endsWith('.js') && !polyfill.endsWith('.module.js')
)
.map((polyfill) => (
<script
key={polyfill}
nonce={this.props.nonce}
crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
}
noModule={true}
src={`${assetPrefix}/_next/${polyfill}${devOnlyCacheBusterQueryString}`}
/>
))
} }
static getInlineScriptSource(documentProps: Readonly<DocumentProps>): string { static getInlineScriptSource(documentProps: Readonly<DocumentProps>): string {
...@@ -752,6 +805,7 @@ export class NextScript extends Component<OriginProps> { ...@@ -752,6 +805,7 @@ export class NextScript extends Component<OriginProps> {
unstable_runtimeJS, unstable_runtimeJS,
docComponentsRendered, docComponentsRendered,
devOnlyCacheBusterQueryString, devOnlyCacheBusterQueryString,
disableOptimizedLoading,
} = this.context } = this.context
const disableRuntimeJS = unstable_runtimeJS === false const disableRuntimeJS = unstable_runtimeJS === false
...@@ -841,10 +895,16 @@ export class NextScript extends Component<OriginProps> { ...@@ -841,10 +895,16 @@ export class NextScript extends Component<OriginProps> {
}} }}
/> />
)} )}
{!disableRuntimeJS && this.getPolyfillScripts()} {disableOptimizedLoading &&
{!disableRuntimeJS && this.getPreNextScripts()} !disableRuntimeJS &&
{disableRuntimeJS ? null : this.getDynamicChunks(files)} this.getPolyfillScripts()}
{disableRuntimeJS ? null : this.getScripts(files)} {disableOptimizedLoading &&
!disableRuntimeJS &&
this.getPreNextScripts()}
{disableOptimizedLoading &&
!disableRuntimeJS &&
this.getDynamicChunks(files)}
{disableOptimizedLoading && !disableRuntimeJS && this.getScripts(files)}
</> </>
) )
} }
......
module.exports = {
experimental: { disableOptimizedLoading: false },
}
import Link from 'next/link'
export default () => (
<div>
<h1>Hello World!</h1>
<br />
<br />
<Link href="/page1">Without font</Link>
</div>
)
export default () => <h1>Hello World!</h1>
export const getServerSideProps = () => {
return {
props: {
hello: 'world',
},
}
}
/* eslint-env jest */
import { join } from 'path'
import cheerio from 'cheerio'
import {
nextServer,
nextBuild,
startApp,
stopApp,
renderViaHTTP,
findPort,
launchApp,
killApp,
} from 'next-test-utils'
const appDir = join(__dirname, '../')
let server
let app
jest.setTimeout(1000 * 60 * 5)
const context = {}
function runTests(url) {
it('should render the page', async () => {
const html = await renderViaHTTP(context.appPort, url)
expect(html).toMatch(/Hello World/)
})
it('should not have JS preload links', async () => {
const html = await renderViaHTTP(context.appPort, url)
const $ = cheerio.load(html)
expect($('link[rel=preload]').length).toBe(0)
})
it('should load scripts with defer in head', async () => {
const html = await renderViaHTTP(context.appPort, url)
const $ = cheerio.load(html)
expect($('script[async]').length).toBe(0)
expect($('head script[defer]').length).toBeGreaterThan(0)
})
}
describe('Optimized loading', () => {
describe('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
app = nextServer({
dir: join(__dirname, '../'),
dev: false,
quiet: true,
})
server = await startApp(app)
context.appPort = server.address().port
})
afterAll(() => stopApp(server))
runTests('/')
runTests('/page1')
})
describe('dev mode', () => {
let app
beforeAll(async () => {
context.appPort = await findPort()
app = await launchApp(join(__dirname, '../'), context.appPort)
})
afterAll(() => killApp(app))
runTests('/')
runTests('/page1')
})
})
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