简体   繁体   中英

How can I delay a mutation observer in JavaScript?

I'm a little stuck with my attempts to work with MutationObserver from JS and I hope someone can help me with a possible solution.

I have the below HTML markup:

<div class="box--html">
 <div class="box__body"></div>
</div>

I would like to use a JavaScript mutation observer to find when the elements mentioned above appear on the page in order to insert a script.

What I tried so far, gives me an error in the console.log like:

const observer = new MutationObserver(function (mutation_el) {
 mutation_el.forEach(function (mutation) {
   if(added_node.class == 'box__body') {
     console.log('Resource box appeared'); 
     // some long script
     $(document).ready(function () {...});
     observer.disconnect();
   }
 });
});

observer.observe(document.querySelector(".box--html"), {subtree: false, childList: true});

"Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'" .

If I must insert a delay in this mutationObserver, how should I write the code?

Any advice would be great to solve this, thanks in advance!

Depending on when your JavaScript loads, it's likely that your mutation observer is looking for an element that doesn't yet exist in the DOM. You should poll for the element before attaching an observer to it.

Check out this post for guidance on polling functions: https://davidwalsh.name/javascript-polling

In addition, you could try wrapping your observer in a setTimeout to test that this is in fact the issue. So for example:

setTimeout(() => {
   ...observer code here
}, 5000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM