Skip to content

Commit

Permalink
Improve shadow-dom style handling
Browse files Browse the repository at this point in the history
  • Loading branch information
cezaraugusto committed Dec 10, 2024
1 parent 4fc8a6a commit 63b71d3
Showing 1 changed file with 4 additions and 20 deletions.
24 changes: 4 additions & 20 deletions programs/develop/webpack/plugin-css/common-style-loaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,40 +28,24 @@ function whereToInsertStyleTag(element: HTMLElement) {
}
}

// If the shadowRoot is already available, insert immediately
// If Shadow DOM exists, insert immediately
// @ts-expect-error - global reference.
if (window.__EXTENSION_SHADOW_ROOT__) {
insertElement()
return
}

// Default behavior if MutationObserver is not required
if (!MutationObserver) {
document.head.appendChild(element)
return
}

// Use MutationObserver to wait for the shadow root to be available
// Use a MutationObserver to wait for the Shadow DOM to be created
const observer = new MutationObserver(() => {
// @ts-expect-error - global reference.
if (window.__EXTENSION_SHADOW_ROOT__) {
insertElement()
observer.disconnect() // Stop observing once the shadow root is found
observer.disconnect() // Disconnect once the Shadow DOM is found
}
})

// Observe changes to the `document.body` or `document.head`
observer.observe(document.body, {childList: true, subtree: true})

// Set a timeout to fallback to `document.head` after 5 seconds
setTimeout(() => {
observer.disconnect() // Stop observing after timeout
// @ts-expect-error - global reference.
if (!window.__EXTENSION_SHADOW_ROOT__) {
document.head.appendChild(element)
console.log('Fallback: Element inserted into document.head after timeout')
}
}, 3000)
console.log('Observer waiting for Shadow DOM...')
}

export async function commonStyleLoaders(
Expand Down

0 comments on commit 63b71d3

Please sign in to comment.