Await Element Existence with MutationObserver
As you've encountered in your Chrome extension development, it's crucial to know when an element becomes available on the page. While using intervals to check for its appearance is a common approach, it can be inefficient. Fortunately, jQuery doesn't provide a straightforward solution.
A modern and effective alternative is utilizing the MutationObserver API. This allows you to create a JavaScript function that listens for changes in the DOM tree:
function waitForElm(selector) { return new Promise(resolve => { if (document.querySelector(selector)) { return resolve(document.querySelector(selector)); } const observer = new MutationObserver(mutations => { if (document.querySelector(selector)) { observer.disconnect(); resolve(document.querySelector(selector)); } }); observer.observe(document.body, { childList: true, subtree: true }); }); }
This function takes a selector as input and returns a Promise that resolves when the element is found.
To use it, you can write:
waitForElm('.some-class').then((elm) => { console.log('Element is ready'); console.log(elm.textContent); });
Or, with async/await:
const elm = await waitForElm('.some-class');
The above is the detailed content of How Can I Efficiently Await Element Existence in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!