MCPcopy
hub / github.com/vercel/next.js / onHeadCommit

Function onHeadCommit

packages/next/src/client/index.tsx:694–764  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

692 }
693
694 function onHeadCommit(): void {
695 if (
696 // Turbopack has it's own css injection handling, this code ends up removing the CSS.
697 !process.env.TURBOPACK &&
698 // We use `style-loader` in development, so we don't need to do anything
699 // unless we're in production:
700 process.env.NODE_ENV === 'production' &&
701 // We can skip this during hydration. Running it wont cause any harm, but
702 // we may as well save the CPU cycles:
703 styleSheets &&
704 // Ensure this render was not canceled
705 !canceled
706 ) {
707 const desiredHrefs: Set<string> = new Set(styleSheets.map((s) => s.href))
708 const currentStyleTags: HTMLStyleElement[] =
709 looseToArray<HTMLStyleElement>(
710 document.querySelectorAll('style[data-n-href]')
711 )
712 const currentHrefs: string[] = currentStyleTags.map(
713 (tag) => tag.getAttribute('data-n-href')!
714 )
715
716 // Toggle `<style>` tags on or off depending on if they're needed:
717 for (let idx = 0; idx < currentHrefs.length; ++idx) {
718 if (desiredHrefs.has(currentHrefs[idx])) {
719 currentStyleTags[idx].removeAttribute('media')
720 } else {
721 currentStyleTags[idx].setAttribute('media', 'x')
722 }
723 }
724
725 // Reorder styles into intended order:
726 let referenceNode: Element | null = document.querySelector(
727 'noscript[data-n-css]'
728 )
729 if (
730 // This should be an invariant:
731 referenceNode
732 ) {
733 styleSheets.forEach(({ href }: { href: string }) => {
734 const targetTag: Element | null = document.querySelector(
735 `style[data-n-href="${href}"]`
736 )
737 if (
738 // This should be an invariant:
739 targetTag
740 ) {
741 referenceNode!.parentNode!.insertBefore(
742 targetTag,
743 referenceNode!.nextSibling
744 )
745 referenceNode = targetTag
746 }
747 })
748 }
749
750 // Finally, clean up server rendered stylesheets:
751 looseToArray<HTMLLinkElement>(

Callers

nothing calls this directly

Calls 9

looseToArrayFunction · 0.85
getAttributeMethod · 0.80
insertBeforeMethod · 0.80
mapMethod · 0.45
hasMethod · 0.45
setAttributeMethod · 0.45
forEachMethod · 0.45
removeChildMethod · 0.45

Tested by

no test coverage detected