简体   繁体   English

如何延迟 JavaScript 中的突变观察者?

[英]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.我在尝试使用 JS 的 MutationObserver 时有点受阻,我希望有人可以帮助我找到可能的解决方案。

I have the below HTML markup:我有以下 HTML 标记:

<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.我想使用 JavaScript 突变观察器来查找上述元素何时出现在页面上以便插入脚本。

What I tried so far, gives me an error in the console.log like:到目前为止我尝试过的,在 console.log 中给了我一个错误,如:

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'" . "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?如果我必须在这个mutationObserver中插入一个延迟,我应该如何编写代码?

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.根据您的 JavaScript 加载时间,您的变异观察者很可能正在寻找 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查看此帖子以获取有关轮询功能的指导: 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.此外,您可以尝试将您的观察者包装在 setTimeout 中以测试这实际上是问题所在。 So for example:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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