Unverified Commit db7d7c7d authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Add Experimental CSS Before Anchor (#8803)

This simplifies the CSS insert function and fixes its edge cases around nextSibling by inserting before the anchor instead of after it.
parent 9b0c641b
...@@ -565,30 +565,20 @@ export default async function getBaseWebpackConfig( ...@@ -565,30 +565,20 @@ export default async function getBaseWebpackConfig(
// By default, style-loader injects CSS into the bottom // By default, style-loader injects CSS into the bottom
// of <head>. This causes ordering problems between dev // of <head>. This causes ordering problems between dev
// and prod. To fix this, we render a <noscript> tag as // and prod. To fix this, we render a <noscript> tag as
// an "anchor" for the styles to be placed after. These // an anchor for the styles to be placed before. These
// styles will be applied _before_ <style jsx global>. // styles will be applied _before_ <style jsx global>.
insert: (element: Node) => { insert: (element: Node) => {
const parent = document.querySelector('head') as Element // These elements should always exist. If they do not,
const anchor = document.querySelector( // this code should fail.
const anchorElement = document.querySelector(
'#__next_css__DO_NOT_USE__' '#__next_css__DO_NOT_USE__'
) )!
const parentNode = anchorElement.parentNode! // Normally <head>
// @ts-ignore
const lastInsert = window.__lastInsertedByStyleLoader // Each style tag should be placed right before our
// anchor. By inserting before and not after, we do not
if (lastInsert && lastInsert.nextSibling) { // need to track the last inserted element.
// if a style element was already inserted, insert after parentNode.insertBefore(element, anchorElement)
parent.insertBefore(element, lastInsert.nextSibling)
} else if (anchor && anchor.nextSibling) {
// else, insert after the anchor
parent.insertBefore(element, anchor.nextSibling)
} else {
// fallback to inserting in last position into head
parent.appendChild(element)
}
// @ts-ignore
window.__lastInsertedByStyleLoader = element
}, },
}, },
}, },
......
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