How To Wait For Scripts To Be Loaded
I am building a Chrome extension and in my contentScript, I have a function which loops all the elements and check whether it has rel='preconnect' attribute. If true,
Solution 1:
The proper tool for this task is MutationObserver that monitors DOM modifications.
Since MutationObserver at document_start can slow down the page (even if just by a little), we'll only observe the <head>
element, which is super-fast due to the small amount of elements there.
// there's no HEAD yet at document-start, let's wait until we have itnewMutationObserver((mutations, observer) => {
if (document.head) {
observer.disconnect();
monitorLinks();
}
}).observe(document.documentElement, {childList: true});
functionmonitorLinks() {
constonMutation = mutations => {
for (const {addedNodes} of mutations) {
for (const n of addedNodes) {
if (n.nodeName === 'LINK' && n.rel === 'preconnect') {
processLink(n);
}
}
}
};
// the HEAD may have some children alreadyonMutation([{
addedNodes: document.getElementsByTagName('link'),
}]);
// watch for the newly added children of HEADnewMutationObserver(onMutation).observe(document.head, {childList: true});
}
functionprocessLink(link) {
console.log(link);
}
Post a Comment for "How To Wait For Scripts To Be Loaded"