Last active
December 29, 2019 16:58
-
-
Save gsmartagence/9ef227ab5c737306863f93c3e2de2bac to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| { | |
| "name": "waitForElement.js", | |
| "version": "0.1.0" | |
| } |
This file contains hidden or 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 element to be created | |
| * https://paul.kinlan.me/waiting-for-an-element-to-be-created/ | |
| * ESM version | |
| */ | |
| export const waitForElement = function (selector) { | |
| return new Promise(function (resolve, reject) { | |
| const element = document.querySelector(selector) | |
| if (element) { | |
| resolve(element) | |
| return | |
| } | |
| const observer = new MutationObserver(function (mutations) { | |
| mutations.forEach(function (mutation) { | |
| const nodes = Array.from(mutation.addedNodes) | |
| for (let i = 0; i < nodes.length; i++) { | |
| let node = nodes[i] | |
| if (node.matches && node.matches(selector)) { | |
| observer.disconnect() | |
| resolve(node); | |
| return; | |
| } | |
| } | |
| }) | |
| }) | |
| observer.observe(document.documentElement, { | |
| childList: true, | |
| subtree: true | |
| }) | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment