如何使用javascript与延迟加载HTML元素交互?



我有一个chrome扩展,需要一个页面上的所有项目,并把它们放入一个数组。

function getAllItems() {
return document.getElementsByClassName('items')
}

然而,只有24项自动加载。当你滚动到页面底部时,可能会加载更多的内容。

如何与这些惰性加载项交互?

我建议使用MutationObserver来检测特定节点DOM中的变化,这样您就可以检查是否有更多的元素动态添加,并重新运行代码!

从MDN查看这个例子:

// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for(const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type === 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();

您可能需要在使用"DOMContentLoaded"事件侦听器加载所有项时调用该函数:

window.addEventListener("DOMContentLoaded", function() {
function getAllItems() {
return document.getElementsByClassName('items')
}
}, false);

相关内容

  • 没有找到相关文章

最新更新