JavaScript。检测何时从另一个 js 脚本加载 html 元素

标签 javascript

我正在尝试检测从 3rd 方库加载的 html 元素,例如: 标题为“盒子”的div。应该在不使用延迟的情况下检测到它。

function createBox() {
      var parser = new DOMParser();
      var domString =
        '<div title="box" style="border:solid" class="container"><button>btn</button><span class="intro">Hello</span> <span id="name"> World!</span></div>';
      var html = parser.parseFromString(domString, "text/html");
      document.body.append(html.body.firstChild);
    }

    setTimeout(function() {
      // Do something after 2 seconds
      createBox();
    }, 2000);

    let box = document.querySelector('[title="box"]');
    if (box != null) {
      console.log("box is detected");
    }

最佳答案

如果您知道元素将被追加到哪里,您可以将 MutationObserver 附加到父级,它会在追加子级时运行回调:

function createBox() {
  var parser = new DOMParser();
  var domString =
    '<div title="box" style="border:solid" class="container"><button>btn</button><span class="intro">Hello</span> <span id="name"> World!</span></div>';
  var html = parser.parseFromString(domString, "text/html");
  document.body.append(html.body.firstChild);
}

console.log('start');
setTimeout(function() {
  // Do something after 2 seconds
  createBox();
}, 2000);

new MutationObserver(() => {
  const box = document.querySelector('[title="box"]');
  if (box) {
    console.log("box is detected");
  }
})
  .observe(document.body, { childList: true });

如果您不知道元素将被追加到哪里,但您可以识别该元素(例如使用选择器),您仍然可以使用 MutationObserver,但它会必须通过 subtree: true 观察深层变化,这在变化很大的大页面上可能代价高昂:

console.log('start');
function createBox() {
  var parser = new DOMParser();
  var domString =
    '<div title="box" style="border:solid" class="container"><button>btn</button><span class="intro">Hello</span> <span id="name"> World!</span></div>';
  var html = parser.parseFromString(domString, "text/html");
  outer.append(html.body.firstChild);
}

setTimeout(function() {
  // Do something after 2 seconds
  createBox();
}, 2000);

new MutationObserver((_, observer) => {
  const box = document.querySelector('[title="box"]');
  if (box) {
    console.log("box is detected");
    observer.disconnect();
  }
})
  .observe(document.body, { childList: true, subtree: true });
<div id="outer">outer</div>

关于JavaScript。检测何时从另一个 js 脚本加载 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60472995/

相关文章:

javascript - 在 getJSON 中插入 props 时出错

javascript - jQuery 更改不适用于动态添加的 2 个部分

javascript - ReactJS如何在简单组件的componentDidMount中等待所有API调用结束

javascript - jwplayer v7.xx _.getVideoData 不是函数问题

javascript - 在幻灯片中使用 StopInterval()

javascript - 表单提交后保留数据库查询结果

javascript - 在 </body> 标记之前和在 </html> 标记之前包含 JavaScript 之间有什么区别吗?

javascript - 如何在 angularjs 中一起使用 angular-gridster 和 highcharts-ng 指令

javascript - 如何测试 CasperJS 中是否存在选择器?

javascript - 获取 API 数据、呈现数据以及一般使用它的更好方法是什么