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

Refactor experimental-script component (#24940)

parent 59d50ff7
...@@ -8,7 +8,7 @@ const ScriptCache = new Map() ...@@ -8,7 +8,7 @@ const ScriptCache = new Map()
const LoadCache = new Set() const LoadCache = new Set()
export interface Props extends ScriptHTMLAttributes<HTMLScriptElement> { export interface Props extends ScriptHTMLAttributes<HTMLScriptElement> {
strategy?: 'defer' | 'lazy' | 'dangerouslyBlockRendering' | 'eager' strategy?: 'afterInteraction' | 'lazy' | 'beforeInteraction'
id?: string id?: string
onLoad?: () => void onLoad?: () => void
onError?: () => void onError?: () => void
...@@ -93,8 +93,8 @@ const loadScript = (props: Props): void => { ...@@ -93,8 +93,8 @@ const loadScript = (props: Props): void => {
} }
function handleClientScriptLoad(props: Props) { function handleClientScriptLoad(props: Props) {
const { strategy = 'defer' } = props const { strategy = 'afterInteraction' } = props
if (strategy === 'defer') { if (strategy === 'afterInteraction') {
loadScript(props) loadScript(props)
} else if (strategy === 'lazy') { } else if (strategy === 'lazy') {
window.addEventListener('load', () => { window.addEventListener('load', () => {
...@@ -122,8 +122,7 @@ function Script(props: Props): JSX.Element | null { ...@@ -122,8 +122,7 @@ function Script(props: Props): JSX.Element | null {
src = '', src = '',
onLoad = () => {}, onLoad = () => {},
dangerouslySetInnerHTML, dangerouslySetInnerHTML,
children = '', strategy = 'afterInteraction',
strategy = 'defer',
onError, onError,
preload = false, preload = false,
...restProps ...restProps
...@@ -133,7 +132,7 @@ function Script(props: Props): JSX.Element | null { ...@@ -133,7 +132,7 @@ function Script(props: Props): JSX.Element | null {
const { updateScripts, scripts } = useContext(HeadManagerContext) const { updateScripts, scripts } = useContext(HeadManagerContext)
useEffect(() => { useEffect(() => {
if (strategy === 'defer') { if (strategy === 'afterInteraction') {
loadScript(props) loadScript(props)
} else if (strategy === 'lazy') { } else if (strategy === 'lazy') {
loadLazyScript(props) loadLazyScript(props)
...@@ -144,42 +143,14 @@ function Script(props: Props): JSX.Element | null { ...@@ -144,42 +143,14 @@ function Script(props: Props): JSX.Element | null {
return null return null
} }
if (strategy === 'dangerouslyBlockRendering') { if (strategy === 'afterInteraction') {
const syncProps: Props = { ...restProps }
for (const [k, value] of Object.entries({
src,
onLoad,
onError,
dangerouslySetInnerHTML,
children,
})) {
if (!value) {
continue
}
if (k === 'children') {
syncProps.dangerouslySetInnerHTML = {
__html:
typeof value === 'string'
? value
: Array.isArray(value)
? value.join('')
: '',
}
} else {
;(syncProps as any)[k] = value
}
}
return <script {...syncProps} />
} else if (strategy === 'defer') {
if (updateScripts && preload) { if (updateScripts && preload) {
scripts.defer = (scripts.defer || []).concat([src]) scripts.afterInteraction = (scripts.afterInteraction || []).concat([src])
updateScripts(scripts) updateScripts(scripts)
} }
} else if (strategy === 'eager') { } else if (strategy === 'beforeInteraction') {
if (updateScripts) { if (updateScripts) {
scripts.eager = (scripts.eager || []).concat([ scripts.beforeInteraction = (scripts.beforeInteraction || []).concat([
{ {
src, src,
onLoad, onLoad,
......
...@@ -191,7 +191,7 @@ export type DocumentProps = DocumentInitialProps & { ...@@ -191,7 +191,7 @@ export type DocumentProps = DocumentInitialProps & {
unstable_runtimeJS?: false unstable_runtimeJS?: false
unstable_JsPreload?: false unstable_JsPreload?: false
devOnlyCacheBusterQueryString: string devOnlyCacheBusterQueryString: string
scriptLoader: { defer?: string[]; eager?: any[] } scriptLoader: { afterInteraction?: string[]; beforeInteraction?: any[] }
locale?: string locale?: string
} }
......
...@@ -256,7 +256,7 @@ export class Head extends Component< ...@@ -256,7 +256,7 @@ export class Head extends Component<
}) })
return [ return [
...(scriptLoader.eager || []).map((file) => ( ...(scriptLoader.beforeInteraction || []).map((file) => (
<link <link
key={file.src} key={file.src}
nonce={this.props.nonce} nonce={this.props.nonce}
...@@ -282,7 +282,7 @@ export class Head extends Component< ...@@ -282,7 +282,7 @@ export class Head extends Component<
} }
/> />
)), )),
...(scriptLoader.defer || []).map((file: string) => ( ...(scriptLoader.afterInteraction || []).map((file: string) => (
<link <link
key={file} key={file}
nonce={this.props.nonce} nonce={this.props.nonce}
...@@ -304,14 +304,18 @@ export class Head extends Component< ...@@ -304,14 +304,18 @@ export class Head extends Component<
React.Children.forEach(children, (child: any) => { React.Children.forEach(children, (child: any) => {
if (child.type === Script) { if (child.type === Script) {
if (child.props.strategy === 'eager') { if (child.props.strategy === 'beforeInteraction') {
scriptLoader.eager = (scriptLoader.eager || []).concat([ scriptLoader.beforeInteraction = (
scriptLoader.beforeInteraction || []
).concat([
{ {
...child.props, ...child.props,
}, },
]) ])
return return
} else if (['lazy', 'defer'].includes(child.props.strategy)) { } else if (
['lazy', 'afterInteraction'].includes(child.props.strategy)
) {
scriptLoaderItems.push(child.props) scriptLoaderItems.push(child.props)
return return
} }
...@@ -664,7 +668,8 @@ export class NextScript extends Component<OriginProps> { ...@@ -664,7 +668,8 @@ export class NextScript extends Component<OriginProps> {
getPreNextScripts() { getPreNextScripts() {
const { scriptLoader } = this.context const { scriptLoader } = this.context
return (scriptLoader.eager || []).map((file: ScriptLoaderProps) => { return (scriptLoader.beforeInteraction || []).map(
(file: ScriptLoaderProps) => {
const { strategy, ...props } = file const { strategy, ...props } = file
return ( return (
<script <script
...@@ -675,7 +680,8 @@ export class NextScript extends Component<OriginProps> { ...@@ -675,7 +680,8 @@ export class NextScript extends Component<OriginProps> {
} }
/> />
) )
}) }
)
} }
getScripts(files: DocumentFiles) { getScripts(files: DocumentFiles) {
......
...@@ -21,9 +21,9 @@ export default class MyDocument extends Document { ...@@ -21,9 +21,9 @@ export default class MyDocument extends Document {
href="https://fonts.googleapis.com/css?family=Voces" href="https://fonts.googleapis.com/css?family=Voces"
/> />
<Script <Script
id="documentDefer" id="documentAfterInteraction"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=documentDefer" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=documentAfterInteraction"
strategy="defer" strategy="afterInteraction"
></Script> ></Script>
<Script <Script
id="documentLazy" id="documentLazy"
...@@ -36,9 +36,9 @@ export default class MyDocument extends Document { ...@@ -36,9 +36,9 @@ export default class MyDocument extends Document {
strategy="dangerouslyBlockRendering" strategy="dangerouslyBlockRendering"
></Script> ></Script>
<Script <Script
id="documentEager" id="documentBeforeInteraction"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=documentEager" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=documentBeforeInteraction"
strategy="eager" strategy="beforeInteraction"
></Script> ></Script>
</Head> </Head>
<body> <body>
......
...@@ -4,8 +4,8 @@ const Page = () => { ...@@ -4,8 +4,8 @@ const Page = () => {
return ( return (
<div class="container"> <div class="container">
<Script <Script
id="scriptDefer" id="scriptAfterInteraction"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptDefer" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptAfterInteraction"
preload preload
></Script> ></Script>
<div>index</div> <div>index</div>
......
...@@ -4,9 +4,9 @@ const Page = () => { ...@@ -4,9 +4,9 @@ const Page = () => {
return ( return (
<div class="container"> <div class="container">
<Script <Script
id="scriptEager" id="scriptBeforeInteraction"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptEager" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptBeforeInteraction"
strategy="eager" strategy="beforeInteraction"
></Script> ></Script>
<div>page1</div> <div>page1</div>
</div> </div>
......
import Script from 'next/experimental-script'
const Page = () => {
return (
<div class="container">
<Script
id="scriptBlock"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=dangerouslyBlockRendering"
strategy="dangerouslyBlockRendering"
></Script>
<div>page2</div>
</div>
)
}
export default Page
...@@ -34,7 +34,7 @@ describe('Script Loader', () => { ...@@ -34,7 +34,7 @@ describe('Script Loader', () => {
stopApp(server) stopApp(server)
}) })
it('priority defer', async () => { it('priority afterInteraction', async () => {
let browser let browser
try { try {
browser = await webdriver(appPort, '/') browser = await webdriver(appPort, '/')
...@@ -58,10 +58,10 @@ describe('Script Loader', () => { ...@@ -58,10 +58,10 @@ describe('Script Loader', () => {
expect(endPreloads.length).toBe(0) expect(endPreloads.length).toBe(0)
} }
// Defer script in page // afterInteraction script in page
await test('scriptDefer') await test('scriptAfterInteraction')
// Defer script in _document // afterInteraction script in _document
await test('documentDefer') await test('documentAfterInteraction')
} finally { } finally {
if (browser) await browser.close() if (browser) await browser.close()
} }
...@@ -96,7 +96,7 @@ describe('Script Loader', () => { ...@@ -96,7 +96,7 @@ describe('Script Loader', () => {
} }
}) })
it('priority eager', async () => { it('priority beforeInteraction', async () => {
const html = await renderViaHTTP(appPort, '/page1') const html = await renderViaHTTP(appPort, '/page1')
const $ = cheerio.load(html) const $ = cheerio.load(html)
...@@ -130,17 +130,8 @@ describe('Script Loader', () => { ...@@ -130,17 +130,8 @@ describe('Script Loader', () => {
).toBeGreaterThan(0) ).toBeGreaterThan(0)
} }
test('scriptEager') test('scriptBeforeInteraction')
test('documentEager') test('documentBeforeInteraction')
})
it('priority dangerouslyBlockRendering', async () => {
const html = await renderViaHTTP(appPort, '/page2')
const $ = cheerio.load(html)
// Script is inserted in place
expect($('.container #scriptBlock').length).toBeGreaterThan(0)
expect($('head #documentBlock').length).toBeGreaterThan(0)
}) })
it('onload fires correctly', async () => { it('onload fires correctly', async () => {
......
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