我正在Chrome中开发一个扩展,我想知道:当一个元素出现时,最好的方法是什么?使用纯javascript,间隔检查,直到一个元素存在,或jQuery有一些简单的方法来做到这一点?
当前回答
下面是一个使用MutationObserver api的简单解决方案。
没有jQuery 没有计时器 没有第三方库 基于Promise,并与async/await一起工作
我在几个项目中使用过它。
function waitForElm(selector) {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector));
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
使用它:
waitForElm('.some-class').then((elm) => {
console.log('Element is ready');
console.log(elm.textContent);
});
或者使用async/await:
const elm = await waitForElm('.some-class');
其他回答
insertionQuery库呢?
insertionQuery使用CSS动画回调附加到指定的选择器,在创建元素时运行回调。此方法允许在创建元素时运行回调,而不仅仅是第一次。
从github:
用非dom事件的方式捕获节点。它使用选择器。 它不仅仅是为了更广泛的浏览器支持,在某些方面它可能比DOMMutationObserver更好。 为什么? 因为DOM事件会降低浏览器的速度,而insertionQuery不会 因为DOM Mutation Observer的浏览器支持比insertionQuery少 因为使用insertionQuery,您可以使用选择器过滤DOM更改,而没有性能开销! 广泛的支持! IE10+和其他设备(包括手机)
这是一个纯Javascript函数,它允许你等待任何事情。设置更长的间隔,以占用更少的CPU资源。
/**
* @brief Wait for something to be ready before triggering a timeout
* @param {callback} isready Function which returns true when the thing we're waiting for has happened
* @param {callback} success Function to call when the thing is ready
* @param {callback} error Function to call if we time out before the event becomes ready
* @param {int} count Number of times to retry the timeout (default 300 or 6s)
* @param {int} interval Number of milliseconds to wait between attempts (default 20ms)
*/
function waitUntil(isready, success, error, count, interval){
if (count === undefined) {
count = 300;
}
if (interval === undefined) {
interval = 20;
}
if (isready()) {
success();
return;
}
// The call back isn't ready. We need to wait for it
setTimeout(function(){
if (!count) {
// We have run out of retries
if (error !== undefined) {
error();
}
} else {
// Try again
waitUntil(isready, success, error, count -1, interval);
}
}, interval);
}
要调用它,例如在jQuery中,使用如下代码:
waitUntil(function(){
return $('#myelement').length > 0;
}, function(){
alert("myelement now exists");
}, function(){
alert("I'm bored. I give up.");
});
如果可以的话,我会尽量避开突变观察者,所以我想到了这个。它看起来类似于上面的一些其他答案。该函数将查找给定DOM调用中存在的第一个元素——className是预期的用法,但它也可以接受tagName或Id。如果您正在寻找具有给定类名或标记名的元素数量,则还可以为精确索引添加参数。
async function waitUntilElementExits(domkey,domquery,maxtime){
const delay = (ms) => new Promise(res => setTimeout(res, ms));
for(let i=0; i<maxtime; i=i+200){
await delay(200);
let elm = document[domkey](domquery);
if( (domkey == 'getElementById' && elm) || elm?.[0] ) break;
}
}
// usage
await waitUntilElementExits('getElementByClassName','some_class_name',10000)
你可以试试这个:
const wait_until_element_appear = setInterval(() => {
if ($(element).length !== 0) {
// some code
clearInterval(wait_until_element_appear);
}
}, 0);
这个办法对我很有效
你也可以使用getElementById代替querySelector
这个函数和 https://stackoverflow.com/a/61511955/10798137
async function waitForElementById(id, timeout = null, location = document.body) {
return new Promise((resolve) => {
let element = document.getElementById(id);
if (element) {
return resolve(element);
}
const observer = new MutationObserver(async () => {
let element = document.getElementById(id);
if (element) {
resolve(element);
observer.disconnect();
} else {
if (timeout) {
async function timeOver() {
return new Promise((resolve) => {
setTimeout(() => {
observer.disconnect();
resolve(false);
}, timeout);
});
}
resolve(await timeOver());
}
}
});
observer.observe(location, {
childList: true,
subtree: true,
});
});
使用它
waitForElement("tag_id", 500).then((elm) => {
console.log(elm)
})
Or
var elm = async waitForElement("tag_id", 500)
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 如何禁用谷歌翻译从HTML在Chrome
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- jQuery: keyPress退格键不火?
- XMLHttpRequest Origin null不允许Access-Control-Allow-Origin for file:/// to file:///(无服务器)
- JavaScript: override alert()