Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created March 25, 2021 20:10
Show Gist options
  • Save tomhodgins/11598c6481661c76d64fc5d33fbf2ebb to your computer and use it in GitHub Desktop.
Save tomhodgins/11598c6481661c76d64fc5d33fbf2ebb to your computer and use it in GitHub Desktop.
// Wait for React
function hasReactProperty(tag = document.documentElement) {
return Object.keys(tag).some(key =>
key.includes('__react')
)
}
function isReactRoot(tag) {
return hasReactProperty(tag)
&& tag.parentElement !== null
&& hasReactProperty(tag.parentElement) === false
}
function hasUpgraded(tag = document.documentElement) {
return tag.dataset.upgraded === 'true'
}
/* export default */ function waitForReact(callback = () => {}) {
const mo = new MutationObserver(processReactRoots)
function processReactRoots(entries) {
entries.forEach(({addedNodes}) =>
[...addedNodes]
.filter(isReactRoot)
.filter(tag => hasUpgraded(tag) === false)
.forEach(reactRoot => {
reactRoot.dataset.upgraded = true
callback(reactRoot)
})
)
}
// Do it once right away
processReactRoots([{
addedNodes: document.querySelectorAll('*')
}])
// watch elements
mo.observe(document.documentElement, {
childList: true,
subtree: true
})
}
// Try it!
waitForReact(reactRoot =>
console.warn('processed react root', reactRoot)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment