我正在尝试检测从 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/