Observing Element Addition in the DOM
To receive a notification when an element is added to a webpage, a few approaches are available:
Deprecated Mutation Events:
Previously, mutation events (e.g., DOMNodeInserted) could be used to monitor DOM changes. However, these events are now deprecated.
Continuous Polling:
An outdated approach involves using setInterval() to regularly check for the presence of the desired element:
<code class="js">function checkDOMChange() { // Check for element presence... // Continue polling after 100 milliseconds setTimeout(checkDOMChange, 100); }</code>
This is an inefficient solution that consumes significant CPU resources.
Recommended: MutationObserver
Modern browsers support MutationObserver, which provides an alternative to mutation events. It allows you to observe DOM changes and execute a callback function when an element is added:
<code class="js">const observer = new MutationObserver(mutations => { // Process DOM changes... }); observer.observe(document.documentElement, { childList: true });</code>
By implementing MutationObserver, you can effectively monitor DOM additions without the limitations of deprecated mutation events or the inefficiency of continuous polling.
The above is the detailed content of How to Detect Element Addition in the DOM: Deprecation and Alternatives?. For more information, please follow other related articles on the PHP Chinese website!