Unverified Commit 0441f816 authored by Janicklas Ralph's avatar Janicklas Ralph Committed by GitHub

Changes to the beforeInteractive strategy to make it work for streaming (#31936)

Changes to the beforeInteractive strategy to make it work for streaming

Splitting `beforeInteractive` into two strategies `beforeInteractive` at the _document level and `beforePageRender` for page level <Scripts>
parent 3b8e2f68
...@@ -73,13 +73,30 @@ There are three different loading strategies that can be used: ...@@ -73,13 +73,30 @@ There are three different loading strategies that can be used:
#### beforeInteractive #### beforeInteractive
Scripts that load with the `beforeInteractive` strategy are injected into the initial HTML from the server and run before self-bundled JavaScript is executed. This strategy should be used for any critical scripts that need to be fetched and executed before the page is interactive. Scripts that load with the `beforeInteractive` strategy are injected into the initial HTML from the server and run before self-bundled JavaScript is executed. This strategy should be used for any critical scripts that need to be fetched and executed before any page becomes interactive. This strategy only works inside **\_document.js** and is designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side).
The reason `beforeInteractive` was designed to work only inside `\_document.js` is to support streaming and Suspense functionality. Outside of the `_document`, it's not possible to guarantee the timing or ordering of `beforeInteractive` scripts.
```jsx ```jsx
<Script // In _document.js
src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js" import { Html, Head, Main, NextScript } from 'next/document'
strategy="beforeInteractive" import Script from 'next/script'
/>
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
<Script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"
strategy="beforeInteractive"
></Script>
</body>
</Html>
)
}
``` ```
Examples of scripts that should be loaded as soon as possible with this strategy include: Examples of scripts that should be loaded as soon as possible with this strategy include:
......
...@@ -562,6 +562,10 @@ ...@@ -562,6 +562,10 @@
"title": "script-in-document-page", "title": "script-in-document-page",
"path": "/errors/no-script-in-document-page.md" "path": "/errors/no-script-in-document-page.md"
}, },
{
"title": "before-interactive-script-outside-document",
"path": "/errors/no-before-interactive-script-outside-document.md"
},
{ {
"title": "script-component-in-head-component", "title": "script-component-in-head-component",
"path": "/errors/no-script-component-in-head-component.md" "path": "/errors/no-script-component-in-head-component.md"
......
# beforeInteractive Script component outside \_document.js
#### Why This Error Occurred
You can't use the `next/script` component with the `beforeInteractive` strategy outside the `_document.js` page. That's because `beforeInteractive` strategy only works inside **\_document.js** and is designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side).
#### Possible Ways to Fix It
If you want a global script, move the script inside `_document.js` page.
```jsx
// In _document.js
import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
<Script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"
strategy="beforeInteractive"
></Script>
</body>
</Html>
)
}
```
- [next-script](https://nextjs.org/docs/basic-features/script#usage)
...@@ -13,13 +13,13 @@ module.exports = { ...@@ -13,13 +13,13 @@ module.exports = {
'link-passhref': require('./rules/link-passhref'), 'link-passhref': require('./rules/link-passhref'),
'no-document-import-in-page': require('./rules/no-document-import-in-page'), 'no-document-import-in-page': require('./rules/no-document-import-in-page'),
'no-head-import-in-document': require('./rules/no-head-import-in-document'), 'no-head-import-in-document': require('./rules/no-head-import-in-document'),
'no-script-in-document': require('./rules/no-script-in-document'),
'no-script-component-in-head': require('./rules/no-script-component-in-head'), 'no-script-component-in-head': require('./rules/no-script-component-in-head'),
'no-server-import-in-page': require('./rules/no-server-import-in-page'), 'no-server-import-in-page': require('./rules/no-server-import-in-page'),
'no-typos': require('./rules/no-typos'), 'no-typos': require('./rules/no-typos'),
'no-duplicate-head': require('./rules/no-duplicate-head'), 'no-duplicate-head': require('./rules/no-duplicate-head'),
'inline-script-id': require('./rules/inline-script-id'), 'inline-script-id': require('./rules/inline-script-id'),
'next-script-for-ga': require('./rules/next-script-for-ga'), 'next-script-for-ga': require('./rules/next-script-for-ga'),
'no-before-interactive-script-outside-document': require('./rules/no-before-interactive-script-outside-document'),
'no-assign-module-variable': require('./rules/no-assign-module-variable'), 'no-assign-module-variable': require('./rules/no-assign-module-variable'),
}, },
configs: { configs: {
...@@ -40,12 +40,12 @@ module.exports = { ...@@ -40,12 +40,12 @@ module.exports = {
'@next/next/next-script-for-ga': 1, '@next/next/next-script-for-ga': 1,
'@next/next/no-document-import-in-page': 2, '@next/next/no-document-import-in-page': 2,
'@next/next/no-head-import-in-document': 2, '@next/next/no-head-import-in-document': 2,
'@next/next/no-script-in-document': 2,
'@next/next/no-script-component-in-head': 2, '@next/next/no-script-component-in-head': 2,
'@next/next/no-server-import-in-page': 2, '@next/next/no-server-import-in-page': 2,
'@next/next/no-typos': 1, '@next/next/no-typos': 1,
'@next/next/no-duplicate-head': 2, '@next/next/no-duplicate-head': 2,
'@next/next/inline-script-id': 2, '@next/next/inline-script-id': 2,
'@next/next/no-before-interactive-script-outside-document': 1,
'@next/next/no-assign-module-variable': 2, '@next/next/no-assign-module-variable': 2,
}, },
}, },
......
const path = require('path')
module.exports = {
meta: {
docs: {
description:
'Disallow using next/script beforeInteractive strategy outside the next/_document component',
recommended: true,
url: 'https://nextjs.org/docs/messages/no-before-interactive-script-outside-document',
},
},
create: function (context) {
let scriptImportName = null
return {
'ImportDeclaration[source.value="next/script"] > ImportDefaultSpecifier'(
node
) {
scriptImportName = node.local.name
},
JSXOpeningElement(node) {
if (!scriptImportName) {
return
}
if (node.name && node.name.name !== scriptImportName) {
return
}
const strategy = node.attributes.find(
(child) => child.name && child.name.name === 'strategy'
)
if (!strategy || strategy?.value?.value !== 'beforeInteractive') {
return
}
const document = context.getFilename().split('pages')[1]
if (document && path.parse(document).name.startsWith('_document')) {
return
}
context.report({
node,
message:
'next/script beforeInteractive strategy should only be used inside next/_document. See: https://nextjs.org/docs/messages/no-before-interactive-script-outside-document',
})
},
}
},
}
const path = require('path')
module.exports = {
meta: {
docs: {
description: 'Disallow importing next/script inside pages/_document.js',
recommended: true,
url: 'https://nextjs.org/docs/messages/no-script-in-document-page',
},
},
create: function (context) {
return {
ImportDeclaration(node) {
if (node.source.value !== 'next/script') {
return
}
const document = context.getFilename().split('pages')[1]
if (!document || !path.parse(document).name.startsWith('_document')) {
return
}
context.report({
node,
message: `next/script should not be used in pages/_document.js. See: https://nextjs.org/docs/messages/no-script-in-document-page`,
})
},
}
},
}
...@@ -108,14 +108,14 @@ const loadScript = (props: ScriptProps): void => { ...@@ -108,14 +108,14 @@ const loadScript = (props: ScriptProps): void => {
document.body.appendChild(el) document.body.appendChild(el)
} }
function handleClientScriptLoad(props: ScriptProps) { export function handleClientScriptLoad(props: ScriptProps) {
const { strategy = 'afterInteractive' } = props const { strategy = 'afterInteractive' } = props
if (strategy === 'afterInteractive') { if (strategy === 'lazyOnload') {
loadScript(props)
} else if (strategy === 'lazyOnload') {
window.addEventListener('load', () => { window.addEventListener('load', () => {
requestIdleCallback(() => loadScript(props)) requestIdleCallback(() => loadScript(props))
}) })
} else {
loadScript(props)
} }
} }
...@@ -129,8 +129,20 @@ function loadLazyScript(props: ScriptProps) { ...@@ -129,8 +129,20 @@ function loadLazyScript(props: ScriptProps) {
} }
} }
function addBeforeInteractiveToCache() {
const scripts = [
...document.querySelectorAll('[data-nscript="beforeInteractive"]'),
...document.querySelectorAll('[data-nscript="beforePageRender"]'),
]
scripts.forEach((script) => {
const cacheKey = script.id || script.getAttribute('src')
LoadCache.add(cacheKey)
})
}
export function initScriptLoader(scriptLoaderItems: ScriptProps[]) { export function initScriptLoader(scriptLoaderItems: ScriptProps[]) {
scriptLoaderItems.forEach(handleClientScriptLoad) scriptLoaderItems.forEach(handleClientScriptLoad)
addBeforeInteractiveToCache()
} }
function Script(props: ScriptProps): JSX.Element | null { function Script(props: ScriptProps): JSX.Element | null {
......
...@@ -586,6 +586,7 @@ export async function renderToHTML( ...@@ -586,6 +586,7 @@ export async function renderToHTML(
App.getInitialProps === (App as any).origGetInitialProps App.getInitialProps === (App as any).origGetInitialProps
const hasPageGetInitialProps = !!(Component as any)?.getInitialProps const hasPageGetInitialProps = !!(Component as any)?.getInitialProps
const hasPageScripts = (Component as any)?.unstable_scriptLoader
const pageIsDynamic = isDynamicRoute(pathname) const pageIsDynamic = isDynamicRoute(pathname)
...@@ -774,6 +775,14 @@ export async function renderToHTML( ...@@ -774,6 +775,14 @@ export async function renderToHTML(
let head: JSX.Element[] = defaultHead(inAmpMode) let head: JSX.Element[] = defaultHead(inAmpMode)
let initialScripts: any = {}
if (hasPageScripts) {
initialScripts.beforeInteractive = []
.concat(hasPageScripts())
.filter((script: any) => script.props.strategy === 'beforeInteractive')
.map((script: any) => script.props)
}
let scriptLoader: any = {} let scriptLoader: any = {}
const nextExport = const nextExport =
!isSSG && (renderOpts.nextExport || (dev && (isAutoExport || isFallback))) !isSSG && (renderOpts.nextExport || (dev && (isAutoExport || isFallback)))
...@@ -823,7 +832,7 @@ export async function renderToHTML( ...@@ -823,7 +832,7 @@ export async function renderToHTML(
updateScripts: (scripts) => { updateScripts: (scripts) => {
scriptLoader = scripts scriptLoader = scripts
}, },
scripts: {}, scripts: initialScripts,
mountedInstances: new Set(), mountedInstances: new Set(),
}} }}
> >
......
...@@ -16,6 +16,7 @@ import { ...@@ -16,6 +16,7 @@ import {
isAssetError, isAssetError,
markAssetError, markAssetError,
} from '../../../client/route-loader' } from '../../../client/route-loader'
import { handleClientScriptLoad } from '../../../client/script'
import isError, { getProperError } from '../../../lib/is-error' import isError, { getProperError } from '../../../lib/is-error'
import { denormalizePagePath } from '../../../server/denormalize-page-path' import { denormalizePagePath } from '../../../server/denormalize-page-path'
import { normalizeLocalePath } from '../i18n/normalize-locale-path' import { normalizeLocalePath } from '../i18n/normalize-locale-path'
...@@ -1275,6 +1276,15 @@ export default class Router implements BaseRouter { ...@@ -1275,6 +1276,15 @@ export default class Router implements BaseRouter {
) )
let { error, props, __N_SSG, __N_SSP } = routeInfo let { error, props, __N_SSG, __N_SSP } = routeInfo
const component: any = routeInfo.Component
if (component && component.unstable_scriptLoader) {
const scripts = [].concat(component.unstable_scriptLoader())
scripts.forEach((script: any) => {
handleClientScriptLoad(script.props)
})
}
// handle redirect on client-transition // handle redirect on client-transition
if ((__N_SSG || __N_SSP) && props) { if ((__N_SSG || __N_SSP) && props) {
if (props.pageProps && props.pageProps.__N_REDIRECT) { if (props.pageProps && props.pageProps.__N_REDIRECT) {
......
...@@ -12,7 +12,7 @@ describe('experimental.nextScriptWorkers: false with no Partytown dependency', ( ...@@ -12,7 +12,7 @@ describe('experimental.nextScriptWorkers: false with no Partytown dependency', (
files: { files: {
'pages/index.js': ` 'pages/index.js': `
import Script from 'next/script' import Script from 'next/script'
export default function Page() { export default function Page() {
return ( return (
<> <>
...@@ -68,7 +68,7 @@ describe('experimental.nextScriptWorkers: true with required Partytown dependenc ...@@ -68,7 +68,7 @@ describe('experimental.nextScriptWorkers: true with required Partytown dependenc
files: { files: {
'pages/index.js': ` 'pages/index.js': `
import Script from 'next/script' import Script from 'next/script'
export default function Page() { export default function Page() {
return ( return (
<> <>
...@@ -123,7 +123,7 @@ describe('experimental.nextScriptWorkers: true with required Partytown dependenc ...@@ -123,7 +123,7 @@ describe('experimental.nextScriptWorkers: true with required Partytown dependenc
`document.querySelectorAll('script[type="text/partytown"]').length` `document.querySelectorAll('script[type="text/partytown"]').length`
) )
expect(predefinedWorkerScripts).toEqual(1) expect(predefinedWorkerScripts).toBeGreaterThan(0)
await waitFor(1000) await waitFor(1000)
...@@ -132,7 +132,7 @@ describe('experimental.nextScriptWorkers: true with required Partytown dependenc ...@@ -132,7 +132,7 @@ describe('experimental.nextScriptWorkers: true with required Partytown dependenc
`document.querySelectorAll('script[type="text/partytown-x"]').length` `document.querySelectorAll('script[type="text/partytown-x"]').length`
) )
expect(processedWorkerScripts).toEqual(1) expect(processedWorkerScripts).toBeGreaterThan(0)
} finally { } finally {
if (browser) await browser.close() if (browser) await browser.close()
} }
...@@ -183,7 +183,7 @@ describe('experimental.nextScriptWorkers: true with config override', () => { ...@@ -183,7 +183,7 @@ describe('experimental.nextScriptWorkers: true with config override', () => {
`, `,
'pages/index.js': ` 'pages/index.js': `
import Script from 'next/script' import Script from 'next/script'
export default function Page() { export default function Page() {
return ( return (
<> <>
......
...@@ -15,11 +15,6 @@ function MyApp({ Component, pageProps }) { ...@@ -15,11 +15,6 @@ function MyApp({ Component, pageProps }) {
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=documentLazyOnload" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=documentLazyOnload"
strategy="lazyOnload" strategy="lazyOnload"
/> />
<Script
id="documentBeforeInteractive"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=documentBeforeInteractive"
strategy="beforeInteractive"
/>
<Component {...pageProps} /> <Component {...pageProps} />
</> </>
) )
......
import * as React from 'react' import * as React from 'react'
/// @ts-ignore /// @ts-ignore
import Document, { Main, NextScript, Head, Html } from 'next/document' import { Main, NextScript, Head, Html } from 'next/document'
import Script from 'next/script'
export default class MyDocument extends Document { export default function Document() {
constructor(props) { return (
super(props) <Html>
const { __NEXT_DATA__, ids } = props <Head>
if (ids) { <link
__NEXT_DATA__.ids = ids rel="stylesheet"
} href="https://fonts.googleapis.com/css?family=Voces"
} />
<Script
render() { id="scriptBeforeInteractive"
return ( src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptBeforeInteractive"
<Html> strategy="beforeInteractive"
<Head> ></Script>
<link </Head>
rel="stylesheet" <body>
href="https://fonts.googleapis.com/css?family=Voces" <Main />
/> <NextScript />
</Head> <div id="text" />
<body> </body>
<Main /> </Html>
<NextScript /> )
<div id="text" />
</body>
</Html>
)
}
} }
...@@ -3,14 +3,19 @@ import Script from 'next/script' ...@@ -3,14 +3,19 @@ import Script from 'next/script'
const Page = () => { const Page = () => {
return ( return (
<div class="container"> <div class="container">
<Script
id="scriptBeforeInteractive"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptBeforeInteractive"
strategy="beforeInteractive"
></Script>
<div>page1</div> <div>page1</div>
</div> </div>
) )
} }
Page.unstable_scriptLoader = () => {
return (
<Script
id="scriptBeforePageRender"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptBeforePageRender"
strategy="beforePageRender"
></Script>
)
}
export default Page export default Page
import Script from 'next/script'
const Page = () => {
return (
<div class="container">
<Script
id="scriptBeforePageRenderOld"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptBeforePageRender"
strategy="beforeInteractive"
></Script>
<div>page6</div>
</div>
)
}
export default Page
...@@ -127,7 +127,27 @@ describe('Next.js Script - Primary Strategies', () => { ...@@ -127,7 +127,27 @@ describe('Next.js Script - Primary Strategies', () => {
} }
test('scriptBeforeInteractive') test('scriptBeforeInteractive')
test('documentBeforeInteractive') })
// Warning - Will be removed in the next major release
it('priority beforeInteractive - older version', async () => {
const html = await renderViaHTTP(appPort, '/page6')
const $ = cheerio.load(html)
function test(id) {
const script = $(`#${id}`)
// Renders script tag
expect(script.length).toBe(1)
expect(script.attr('data-nscript')).toBeDefined()
// Script is inserted before NextScripts
expect(
$(`#${id} ~ script[src^="/_next/static/chunks/main"]`).length
).toBeGreaterThan(0)
}
test('scriptBeforePageRenderOld')
}) })
it('priority beforeInteractive on navigate', async () => { it('priority beforeInteractive on navigate', async () => {
...@@ -137,7 +157,7 @@ describe('Next.js Script - Primary Strategies', () => { ...@@ -137,7 +157,7 @@ describe('Next.js Script - Primary Strategies', () => {
// beforeInteractive scripts should load once // beforeInteractive scripts should load once
let documentBIScripts = await browser.elementsByCss( let documentBIScripts = await browser.elementsByCss(
'[src$="documentBeforeInteractive"]' '[src$="scriptBeforeInteractive"]'
) )
expect(documentBIScripts.length).toBe(1) expect(documentBIScripts.length).toBe(1)
...@@ -146,16 +166,11 @@ describe('Next.js Script - Primary Strategies', () => { ...@@ -146,16 +166,11 @@ describe('Next.js Script - Primary Strategies', () => {
await browser.waitForElementByCss('.container') await browser.waitForElementByCss('.container')
const script = await browser.elementById('scriptBeforeInteractive')
// Ensure beforeInteractive script isn't duplicated on navigation // Ensure beforeInteractive script isn't duplicated on navigation
documentBIScripts = await browser.elementsByCss( documentBIScripts = await browser.elementsByCss(
'[src$="documentBeforeInteractive"]' '[src$="scriptBeforeInteractive"]'
) )
expect(documentBIScripts.length).toBe(1) expect(documentBIScripts.length).toBe(1)
// Renders script tag
expect(script).toBeDefined()
} finally { } finally {
if (browser) await browser.close() if (browser) await browser.close()
} }
......
import rule from '@next/eslint-plugin-next/lib/rules/no-script-in-document' import rule from '@next/eslint-plugin-next/lib/rules/no-before-interactive-script-outside-document'
import { RuleTester } from 'eslint' import { RuleTester } from 'eslint'
;(RuleTester as any).setDefaultConfig({ ;(RuleTester as any).setDefaultConfig({
parserOptions: { parserOptions: {
...@@ -12,79 +12,43 @@ import { RuleTester } from 'eslint' ...@@ -12,79 +12,43 @@ import { RuleTester } from 'eslint'
}) })
const ruleTester = new RuleTester() const ruleTester = new RuleTester()
ruleTester.run('no-script-import-in-document', rule, { ruleTester.run('no-before-interactive-script-outside-document', rule, {
valid: [ valid: [
{ {
code: `import Document, { Html, Head, Main, NextScript } from 'next/document' code: `
import Document, { Html, Main, NextScript } from 'next/document'
import Script from 'next/script'
class MyDocument extends Document { class MyDocument extends Document {
static async getInitialProps(ctx) {
//...
}
render() {
return (
<Html>
<Head/>
</Html>
)
}
}
export default MyDocument
`,
filename: 'pages/_document.js',
},
{
code: `import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
render() { render() {
return ( return (
<Html> <Html>
<Head> <Head>
<meta charSet="utf-8" /> <meta charSet="utf-8" />
</Head> </Head>
<body>
<Main />
<NextScript />
<Script
id="scriptBeforeInteractive"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptBeforeInteractive"
strategy="beforeInteractive"
></Script>
</body>
</Html> </Html>
) )
} }
} }
export default MyDocument
`,
filename: 'pages/_document.tsx',
},
],
invalid: [
{
code: `
import Document, { Html, Main, NextScript } from 'next/document'
import Script from 'next/script'
class MyDocument extends Document {
render() {
return (
<Html>
<Head />
</Html>
)
}
}
export default MyDocument export default MyDocument
`, `,
filename: 'pages/_document.js', filename: 'pages/_document.js',
errors: [
{
message: `next/script should not be used in pages/_document.js. See: https://nextjs.org/docs/messages/no-script-in-document-page`,
},
],
}, },
{ {
code: ` code: `
import Document, { Html, Main, NextScript } from 'next/document' import Document, { Html, Main, NextScript } from 'next/document'
import NextScriptTag from 'next/script' import ScriptComponent from 'next/script'
class MyDocument extends Document { class MyDocument extends Document {
render() { render() {
return ( return (
...@@ -95,19 +59,43 @@ ruleTester.run('no-script-import-in-document', rule, { ...@@ -95,19 +59,43 @@ ruleTester.run('no-script-import-in-document', rule, {
<body> <body>
<Main /> <Main />
<NextScript /> <NextScript />
<NextScriptTag /> <ScriptComponent
id="scriptBeforeInteractive"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptBeforeInteractive"
strategy="beforeInteractive"
></ScriptComponent>
</body> </body>
</Html> </Html>
) )
} }
} }
export default MyDocument export default MyDocument
`, `,
filename: 'pages/_document.js', filename: 'pages/_document.tsx',
},
],
invalid: [
{
code: `
import Head from "next/head";
import Script from "next/script";
export default function Index() {
return (
<Script
id="scriptBeforeInteractive"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptBeforeInteractive"
strategy="beforeInteractive"
></Script>
);
}`,
filename: 'pages/index.js',
errors: [ errors: [
{ {
message: `next/script should not be used in pages/_document.js. See: https://nextjs.org/docs/messages/no-script-in-document-page`, message:
'next/script beforeInteractive strategy should only be used inside next/_document. See: https://nextjs.org/docs/messages/no-before-interactive-script-outside-document',
}, },
], ],
}, },
......
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