我正在编写一个脚本(扩展),它选择一个 HTML 标签并对其执行一些操作。然而,这个 HTML 标签将在某个给定时间动态加载到页面上,我想在加载后立即检测到它。目前我正在 while 循环中轮询 html 页面(检查未定义),但它严重滞后于页面。有解决办法吗?
$(document).ready(function() {
// some code
var sizesList=document.getElementsByClassName("exp-pdp-size-dropdown-container nsg-form--drop-down--option-container selectBox-options nsg-form--drop-down exp-pdp-size-dropdown exp-pdp-dropdown two-column-dropdown selectBox-dropdown-menu")[0];
while(typeof(sizesList) == 'undefined') {
setTimeout(function() {}, 700)
sizesList=document.getElementsByClassName("exp-pdp-size-dropdown-container nsg-form--drop-down--option-container selectBox-options nsg-form--drop-down exp-pdp-size-dropdown exp-pdp-dropdown two-column-dropdown selectBox-dropdown-menu")[0];
}
// some more code
}
我正在 this 上测试它网页。
最佳答案
页面滞后是因为您正在连续执行sizesList=document.getElementsByClassName(...
连续。setTimeout 是异步的,因此它不会执行任何操作。
要像您期望的那样每 700 毫秒轮询一次,您应该考虑 setInterval
:
setInterval(function() {
if(typeof(sizesList) == 'undefined')
sizesList=document.getElementsBy(...
}, 700)
关于javascript - Chrome 扩展程序轮询 html 滞后页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47384123/