Skip to content

Commit

Permalink
Add data attribute to script component (#28310)
Browse files Browse the repository at this point in the history
Add data attribute `data-nscript` to the script component
  • Loading branch information
janicklas-ralph committed Aug 20, 2021
1 parent 8737ac0 commit 26255a6
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/next/client/script.tsx
Expand Up @@ -35,6 +35,7 @@ const loadScript = (props: ScriptProps): void => {
onLoad = () => {},
dangerouslySetInnerHTML,
children = '',
strategy = 'afterInteractive',
onError,
} = props

Expand Down Expand Up @@ -98,6 +99,8 @@ const loadScript = (props: ScriptProps): void => {
el.setAttribute(attr, value)
}

el.setAttribute('data-nscript', strategy)

document.body.appendChild(el)
}

Expand Down
1 change: 1 addition & 0 deletions packages/next/pages/_document.tsx
Expand Up @@ -84,6 +84,7 @@ function getPreNextScripts(context: HtmlProps, props: OriginProps) {
key={scriptProps.src || index}
defer={!disableOptimizedLoading}
nonce={props.nonce}
data-nscript="beforeInteractive"
crossOrigin={props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN}
/>
)
Expand Down
7 changes: 7 additions & 0 deletions test/integration/script-loader/test/index.test.js
Expand Up @@ -42,12 +42,15 @@ describe('Script Loader', () => {

async function test(id) {
const script = await browser.elementById(id)
const dataAttr = await script.getAttribute('data-nscript')
const endScripts = await browser.elementsByCss(
`#__NEXT_DATA__ ~ #${id}`
)

// Renders script tag
expect(script).toBeDefined()
expect(dataAttr).toBeDefined()

// Script is inserted at the end
expect(endScripts.length).toBe(1)
}
Expand Down Expand Up @@ -77,12 +80,15 @@ describe('Script Loader', () => {

async function test(id) {
const script = await browser.elementById(id)
const dataAttr = await script.getAttribute('data-nscript')
const endScripts = await browser.elementsByCss(
`#__NEXT_DATA__ ~ #${id}`
)

// Renders script tag
expect(script).toBeDefined()
expect(dataAttr).toBeDefined()

// Script is inserted at the end
expect(endScripts.length).toBe(1)
}
Expand All @@ -105,6 +111,7 @@ describe('Script Loader', () => {

// Renders script tag
expect(script.length).toBe(1)
expect(script.attr('data-nscript')).toBeDefined()

// Script is inserted before NextScripts
expect(
Expand Down

0 comments on commit 26255a6

Please sign in to comment.