Javascript DOM : 等待页面上出现特定的 DOM 元素后,在执行代码
Javascript 是异步的,一个常见的痛点是在页面上的 DOM 元素加载之前运行脚本。
处理此问题的一种方法是向文档中添加一个侦听器来侦听该DOMEContentLoaded事件。
document.addEventListener("DOMContentLoaded", function(){
// Code here waits to run until the DOM is loaded.
});
在复杂的场景中——当页面上的多个元素通过 AJAX 加载数据时——上面的脚本不起作用。
我使用下面的代码片段来检查页面上何时出现特定的 DOM 元素,然后运行代码。我是从Stack Overflow 的 Volomike那里拿到的。
const isElementLoaded = async selector => {
while ( document.querySelector(selector) === null) {
await new Promise( resolve => requestAnimationFrame(resolve) )
}
return document.querySelector(selector);
};
// I'm checking for a specific class .file-item and then running code. You can also check for an id or an element.
isElementLoaded('.file-item').then((selector) => {
// Run code here.
});
这段代码很聪明,因为它循环查找特定的选择器并返回一个 Promise。

浙公网安备 33010602011771号