Unverified Commit 82dce6ce authored by Houssein Djirdeh's avatar Houssein Djirdeh Committed by GitHub

[Script] Allow `next/script` to be placed in `_document` body (#37894)

Fixes https://github.com/vercel/next.js/issues/37741. Allows `next/script` to be placed inside of `_document` body in addition to `Head`.

## Bug

- [X] Related issues linked using `fixes #number`
- [X] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
parent 0f33c0cb
...@@ -99,6 +99,8 @@ export default function Document() { ...@@ -99,6 +99,8 @@ export default function Document() {
} }
``` ```
> **Note**: Scripts with `beforeInteractive` will always be injected inside the `head` of the HTML document regardless of where it's placed in `_document.js`.
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:
- Bot detectors - Bot detectors
......
...@@ -8,6 +8,7 @@ import type { ...@@ -8,6 +8,7 @@ import type {
DocumentInitialProps, DocumentInitialProps,
DocumentProps, DocumentProps,
DocumentType, DocumentType,
NEXT_DATA,
} from '../shared/lib/utils' } from '../shared/lib/utils'
import { BuildManifest, getPageFiles } from '../server/get-page-files' import { BuildManifest, getPageFiles } from '../server/get-page-files'
import { cleanAmpPath } from '../server/utils' import { cleanAmpPath } from '../server/utils'
...@@ -87,6 +88,59 @@ function hasComponentProps(child: any): child is React.ReactElement { ...@@ -87,6 +88,59 @@ function hasComponentProps(child: any): child is React.ReactElement {
return !!child && !!child.props return !!child && !!child.props
} }
function handleDocumentScriptLoaderItems(
scriptLoader: { beforeInteractive?: any[] },
__NEXT_DATA__: NEXT_DATA,
props: any
): void {
if (!props.children) return
const scriptLoaderItems: ScriptProps[] = []
const children = Array.isArray(props.children)
? props.children
: [props.children]
const headChildren = children.find(
(child: React.ReactElement) => child.type === Head
)?.props?.children
const bodyChildren = children.find(
(child: React.ReactElement) => child.type === 'body'
)?.props?.children
// Scripts with beforeInteractive can be placed inside Head or <body> so children of both needs to be traversed
const combinedChildren = [
...(Array.isArray(headChildren) ? headChildren : [headChildren]),
...(Array.isArray(bodyChildren) ? bodyChildren : [bodyChildren]),
]
React.Children.forEach(combinedChildren, (child: any) => {
if (!child) return
if (child.type === Script) {
if (child.props.strategy === 'beforeInteractive') {
scriptLoader.beforeInteractive = (
scriptLoader.beforeInteractive || []
).concat([
{
...child.props,
},
])
return
} else if (
['lazyOnload', 'afterInteractive', 'worker'].includes(
child.props.strategy
)
) {
scriptLoaderItems.push(child.props)
return
}
}
})
__NEXT_DATA__.scriptLoader = scriptLoaderItems
}
function getPreNextWorkerScripts(context: HtmlProps, props: OriginProps) { function getPreNextWorkerScripts(context: HtmlProps, props: OriginProps) {
const { assetPrefix, scriptLoader, crossOrigin, nextScriptWorkers } = context const { assetPrefix, scriptLoader, crossOrigin, nextScriptWorkers } = context
...@@ -340,9 +394,16 @@ export function Html( ...@@ -340,9 +394,16 @@ export function Html(
HTMLHtmlElement HTMLHtmlElement
> >
) { ) {
const { inAmpMode, docComponentsRendered, locale } = useContext(HtmlContext) const {
inAmpMode,
docComponentsRendered,
locale,
scriptLoader,
__NEXT_DATA__,
} = useContext(HtmlContext)
docComponentsRendered.Html = true docComponentsRendered.Html = true
handleDocumentScriptLoaderItems(scriptLoader, __NEXT_DATA__, props)
return ( return (
<html <html
...@@ -605,40 +666,6 @@ export class Head extends Component<HeadProps> { ...@@ -605,40 +666,6 @@ export class Head extends Component<HeadProps> {
return getPolyfillScripts(this.context, this.props) return getPolyfillScripts(this.context, this.props)
} }
handleDocumentScriptLoaderItems(children: React.ReactNode): ReactNode[] {
const { scriptLoader } = this.context
const scriptLoaderItems: ScriptProps[] = []
const filteredChildren: ReactNode[] = []
React.Children.forEach(children, (child: any) => {
if (child.type === Script) {
if (child.props.strategy === 'beforeInteractive') {
scriptLoader.beforeInteractive = (
scriptLoader.beforeInteractive || []
).concat([
{
...child.props,
},
])
return
} else if (
['lazyOnload', 'afterInteractive', 'worker'].includes(
child.props.strategy
)
) {
scriptLoaderItems.push(child.props)
return
}
}
filteredChildren.push(child)
})
this.context.__NEXT_DATA__.scriptLoader = scriptLoaderItems
return filteredChildren
}
makeStylesheetInert(node: ReactNode): ReactNode[] { makeStylesheetInert(node: ReactNode): ReactNode[] {
return React.Children.map(node, (c: any) => { return React.Children.map(node, (c: any) => {
if ( if (
...@@ -740,8 +767,6 @@ export class Head extends Component<HeadProps> { ...@@ -740,8 +767,6 @@ export class Head extends Component<HeadProps> {
children = this.makeStylesheetInert(children) children = this.makeStylesheetInert(children)
} }
children = this.handleDocumentScriptLoaderItems(children)
let hasAmphtmlRel = false let hasAmphtmlRel = false
let hasCanonicalRel = false let hasCanonicalRel = false
......
...@@ -4,7 +4,7 @@ import { NextInstance } from 'test/lib/next-modes/base' ...@@ -4,7 +4,7 @@ import { NextInstance } from 'test/lib/next-modes/base'
import { BrowserInterface } from 'test/lib/browsers/base' import { BrowserInterface } from 'test/lib/browsers/base'
import { check } from 'next-test-utils' import { check } from 'next-test-utils'
describe('beforeInteractive', () => { describe('beforeInteractive in document Head', () => {
let next: NextInstance let next: NextInstance
beforeAll(async () => { beforeAll(async () => {
...@@ -31,9 +31,67 @@ describe('beforeInteractive', () => { ...@@ -31,9 +31,67 @@ describe('beforeInteractive', () => {
) )
} }
`, `,
'pages/index.js': ` 'pages/index.js': `
export default function Home() {
return (
<>
<p>Home page</p>
</>
)
}
`,
},
dependencies: {
react: '17.0.2',
'react-dom': '17.0.2',
},
})
})
afterAll(() => next.destroy())
it('Script is injected server-side', async () => {
let browser: BrowserInterface
try {
browser = await webdriver(next.url, '/')
const script = await browser.eval(
`document.querySelector('script[data-nscript="beforeInteractive"]')`
)
expect(script).not.toBeNull()
} finally {
if (browser) await browser.close()
}
})
})
describe('beforeInteractive in document body', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
'pages/_document.js': `
import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script' import Script from 'next/script'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
<Script
src="https://www.google-analytics.com/analytics.js"
strategy="beforeInteractive"
/>
</body>
</Html>
)
}
`,
'pages/index.js': `
export default function Home() { export default function Home() {
return ( return (
<> <>
...@@ -60,6 +118,7 @@ describe('beforeInteractive', () => { ...@@ -60,6 +118,7 @@ describe('beforeInteractive', () => {
const script = await browser.eval( const script = await browser.eval(
`document.querySelector('script[data-nscript="beforeInteractive"]')` `document.querySelector('script[data-nscript="beforeInteractive"]')`
) )
expect(script).not.toBeNull() expect(script).not.toBeNull()
} finally { } finally {
if (browser) await browser.close() if (browser) await browser.close()
......
...@@ -27,6 +27,10 @@ export default function Document() { ...@@ -27,6 +27,10 @@ export default function Document() {
<body> <body>
<Main /> <Main />
<NextScript /> <NextScript />
<Script
src="https://www.google-analytics.com/analytics.js?a=scriptBeforeInteractive"
strategy="beforeInteractive"
></Script>
<div id="text" /> <div id="text" />
</body> </body>
</Html> </Html>
......
...@@ -159,7 +159,7 @@ describe('Next.js Script - Primary Strategies', () => { ...@@ -159,7 +159,7 @@ describe('Next.js Script - Primary Strategies', () => {
let documentBIScripts = await browser.elementsByCss( let documentBIScripts = await browser.elementsByCss(
'[src$="scriptBeforeInteractive"]' '[src$="scriptBeforeInteractive"]'
) )
expect(documentBIScripts.length).toBe(1) expect(documentBIScripts.length).toBe(2)
await browser.waitForElementByCss('[href="/page1"]') await browser.waitForElementByCss('[href="/page1"]')
await browser.click('[href="/page1"]') await browser.click('[href="/page1"]')
...@@ -170,7 +170,7 @@ describe('Next.js Script - Primary Strategies', () => { ...@@ -170,7 +170,7 @@ describe('Next.js Script - Primary Strategies', () => {
documentBIScripts = await browser.elementsByCss( documentBIScripts = await browser.elementsByCss(
'[src$="scriptBeforeInteractive"]' '[src$="scriptBeforeInteractive"]'
) )
expect(documentBIScripts.length).toBe(1) expect(documentBIScripts.length).toBe(2)
} finally { } finally {
if (browser) await browser.close() if (browser) 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