Created
March 25, 2021 20:10
-
-
Save tomhodgins/11598c6481661c76d64fc5d33fbf2ebb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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