Unverified Commit 039eb817 authored by Gerald Monaco's avatar Gerald Monaco Committed by GitHub

Remove `next-head-count` (#16758)

Removes `next-head-count`, improving support for 3rd party libraries that insert or append new elements to `<head>`.

---

This is more or less what a solution with a `data-` attribute would look like, except that instead of directly searching for elements with that attribute, we serialize the elements expected in `<head>` and then find them/assume ownership of them during initialization (in a manner similar to React's reconciliation) based on their properties.

There are two main assumptions here:
1. Content is served with compression, so duplicate serialization of e.g. inline script or style tags doesn't have a meaningful impact. Storing a hash would be a potential optimization.
2. 3rd party libraries primarily only insert new, unique elements to head. Libraries trying to actively manage elements that overlap with those that Next.js claims ownership of will still be unsupported.

The reason for this roundabout approach is that I'd really like to avoid `data-` if possible, for maximum compatibility. Implicitly adding an attribute could be a breaking change for some class of tools or crawlers and makes it otherwise impossible to insert raw HTML into `<head>`. Adding an unexpected attribute is why the original `class="next-head"` approach was problematic in the first place!

That said, while I don't expect this to be more problematic than `next-head-count` (anything that would break in this new model also should have broken in the old model), if that does end up being the case, it might make sense to just bite the bullet.

Fixes #11012
Closes #16707

---

cc @Timer @timneutkens 
parent 4ba3607d
...@@ -6,6 +6,8 @@ You have a custom `pages/_document.js` that doesn't have the components required ...@@ -6,6 +6,8 @@ You have a custom `pages/_document.js` that doesn't have the components required
#### Possible Ways to Fix It #### Possible Ways to Fix It
Ensure that your `_document.js` is importing and rendering all of the [required components](https://nextjs.org/docs/advanced-features/custom-document). Upgrade Next.js to 9.5.4 or later, which does not require `next-head-count`.
If you can't upgrade right now, ensure that your `_document.js` is importing and rendering all of the [required components](https://nextjs.org/docs/advanced-features/custom-document).
In this case you are most likely not rendering the `<Head>` component imported from `next/document`. In this case you are most likely not rendering the `<Head>` component imported from `next/document`.
import { createElement } from 'react'
import { HeadEntry } from '../next-server/lib/utils'
const DOMAttributeNames: Record<string, string> = { const DOMAttributeNames: Record<string, string> = {
acceptCharset: 'accept-charset', acceptCharset: 'accept-charset',
className: 'class', className: 'class',
...@@ -27,51 +30,63 @@ function reactElementToDOM({ type, props }: JSX.Element): HTMLElement { ...@@ -27,51 +30,63 @@ function reactElementToDOM({ type, props }: JSX.Element): HTMLElement {
return el return el
} }
function updateElements(type: string, components: JSX.Element[]) { function updateElements(
elements: Set<Element>,
components: JSX.Element[],
removeOldTags: boolean
) {
const headEl = document.getElementsByTagName('head')[0] const headEl = document.getElementsByTagName('head')[0]
const headCountEl: HTMLMetaElement = headEl.querySelector( const oldTags = new Set(elements)
'meta[name=next-head-count]'
) as HTMLMetaElement components.forEach((tag) => {
if (process.env.NODE_ENV !== 'production') { if (tag.type === 'title') {
if (!headCountEl) { let title = ''
console.error( if (tag) {
'Warning: next-head-count is missing. https://err.sh/next.js/next-head-count-missing' const { children } = tag.props
) title = typeof children === 'string' ? children : children.join('')
}
if (title !== document.title) document.title = title
return return
} }
}
const headCount = Number(headCountEl.content) const newTag = reactElementToDOM(tag)
const oldTags: Element[] = [] const elementIter = elements.values()
for ( while (true) {
let i = 0, j = headCountEl.previousElementSibling; // Note: We don't use for-of here to avoid needing to polyfill it.
i < headCount; const { done, value } = elementIter.next()
i++, j = j!.previousElementSibling if (value?.isEqualNode(newTag)) {
) { oldTags.delete(value)
if (j!.tagName.toLowerCase() === type) { return
oldTags.push(j!) }
}
} if (done) {
const newTags = (components.map(reactElementToDOM) as HTMLElement[]).filter( break
(newTag) => {
for (let k = 0, len = oldTags.length; k < len; k++) {
const oldTag = oldTags[k]
if (oldTag.isEqualNode(newTag)) {
oldTags.splice(k, 1)
return false
}
} }
return true
} }
)
oldTags.forEach((t) => t.parentNode!.removeChild(t)) elements.add(newTag)
newTags.forEach((t) => headEl.insertBefore(t, headCountEl)) headEl.appendChild(newTag)
headCountEl.content = (headCount - oldTags.length + newTags.length).toString() })
oldTags.forEach((oldTag) => {
if (removeOldTags) {
oldTag.parentNode!.removeChild(oldTag)
}
elements.delete(oldTag)
})
} }
export default function initHeadManager() { export default function initHeadManager(initialHeadEntries: HeadEntry[]) {
const headEl = document.getElementsByTagName('head')[0]
const elements = new Set<Element>(headEl.children)
updateElements(
elements,
initialHeadEntries.map(([type, props]) => createElement(type, props)),
false
)
let updatePromise: Promise<void> | null = null let updatePromise: Promise<void> | null = null
return { return {
...@@ -81,24 +96,7 @@ export default function initHeadManager() { ...@@ -81,24 +96,7 @@ export default function initHeadManager() {
if (promise !== updatePromise) return if (promise !== updatePromise) return
updatePromise = null updatePromise = null
const tags: Record<string, JSX.Element[]> = {} updateElements(elements, head, true)
head.forEach((h) => {
const components = tags[h.type] || []
components.push(h)
tags[h.type] = components
})
const titleComponent = tags.title ? tags.title[0] : null
let title = ''
if (titleComponent) {
const { children } = titleComponent.props
title = typeof children === 'string' ? children : children.join('')
}
if (title !== document.title) document.title = title
;['meta', 'base', 'link', 'style', 'script'].forEach((type) => {
updateElements(type, tags[type] || [])
})
})) }))
}, },
} }
......
...@@ -62,6 +62,7 @@ const { ...@@ -62,6 +62,7 @@ const {
runtimeConfig, runtimeConfig,
dynamicIds, dynamicIds,
isFallback, isFallback,
head: initialHeadData,
} = data } = data
const prefix = assetPrefix || '' const prefix = assetPrefix || ''
...@@ -94,7 +95,7 @@ if (window.__NEXT_P) { ...@@ -94,7 +95,7 @@ if (window.__NEXT_P) {
window.__NEXT_P = [] window.__NEXT_P = []
;(window.__NEXT_P as any).push = register ;(window.__NEXT_P as any).push = register
const headManager = initHeadManager() const headManager = initHeadManager(initialHeadData)
const appElement = document.getElementById('__next') const appElement = document.getElementById('__next')
let lastAppProps: AppProps let lastAppProps: AppProps
......
...@@ -81,6 +81,8 @@ export type BaseContext = { ...@@ -81,6 +81,8 @@ export type BaseContext = {
[k: string]: any [k: string]: any
} }
export type HeadEntry = [string, { [key: string]: any }]
export type NEXT_DATA = { export type NEXT_DATA = {
props: Record<string, any> props: Record<string, any>
page: string page: string
...@@ -98,6 +100,7 @@ export type NEXT_DATA = { ...@@ -98,6 +100,7 @@ export type NEXT_DATA = {
customServer?: boolean customServer?: boolean
gip?: boolean gip?: boolean
appGip?: boolean appGip?: boolean
head: HeadEntry[]
} }
/** /**
......
...@@ -236,6 +236,22 @@ function renderDocument( ...@@ -236,6 +236,22 @@ function renderDocument(
customServer, // whether the user is using a custom server customServer, // whether the user is using a custom server
gip, // whether the page has getInitialProps gip, // whether the page has getInitialProps
appGip, // whether the _app has getInitialProps appGip, // whether the _app has getInitialProps
head: React.Children.toArray(docProps.head || [])
.map((elem) => {
const { children } = elem?.props
return [
elem?.type,
{
...elem?.props,
children: children
? typeof children === 'string'
? children
: children.join('')
: undefined,
},
]
})
.filter(Boolean) as any,
}, },
buildManifest, buildManifest,
docComponentsRendered, docComponentsRendered,
......
...@@ -441,10 +441,6 @@ export class Head extends Component< ...@@ -441,10 +441,6 @@ export class Head extends Component<
)} )}
{children} {children}
{head} {head}
<meta
name="next-head-count"
content={React.Children.count(head || []).toString()}
/>
{inAmpMode && ( {inAmpMode && (
<> <>
<meta <meta
......
...@@ -118,7 +118,7 @@ describe('Build Output', () => { ...@@ -118,7 +118,7 @@ describe('Build Output', () => {
expect(parseFloat(webpackSize) - 752).toBeLessThanOrEqual(0) expect(parseFloat(webpackSize) - 752).toBeLessThanOrEqual(0)
expect(webpackSize.endsWith(' B')).toBe(true) expect(webpackSize.endsWith(' B')).toBe(true)
expect(parseFloat(mainSize) - 7.1).toBeLessThanOrEqual(0) expect(parseFloat(mainSize) - 7.44).toBeLessThanOrEqual(0)
expect(mainSize.endsWith('kB')).toBe(true) expect(mainSize.endsWith('kB')).toBe(true)
expect(parseFloat(frameworkSize) - 41).toBeLessThanOrEqual(0) expect(parseFloat(frameworkSize) - 41).toBeLessThanOrEqual(0)
......
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