-
-
Save Fred-Vatin/d2eabb90d6a786311f7aff0c20517fb5 to your computer and use it in GitHub Desktop.
Wait for an element to exist. ES6, Promise, MutationObserver (version for userScript @require)
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
// MIT Licensed | |
// Author: jwilson8767 | |
/** | |
* Waits for an element satisfying selector to exist, then resolves promise with the element. | |
* Useful for resolving race conditions. | |
* | |
*/ | |
function elementReady(selector) { | |
return new Promise((resolve, reject) => { | |
let el = document.querySelector(selector); | |
if (el) { | |
resolve(el); | |
return | |
} | |
new MutationObserver((mutationRecords, observer) => { | |
// Query for elements matching the specified selector | |
Array.from(document.querySelectorAll(selector)).forEach((element) => { | |
resolve(element); | |
//Once we have resolved we don't need the observer anymore. | |
observer.disconnect(); | |
}); | |
}) | |
.observe(document.documentElement, { | |
childList: true, | |
subtree: true | |
}); | |
}); | |
} |
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
import { elementReady } from "es6-element-ready"; | |
// Simple usage to delete an element if/when it exists: | |
elementReady('#someWidget').then((someWidget)=>{someWidget.remove();}); |
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 all elements be ready | |
Promise.all([elementReady('#element1'), elementReady('#element2'), elementReady('.element3')]).then((matched_elements)=>{ | |
//callback function body | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment