我正在开发一个脚本(扩展程序),它选择一个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网页上对其进行测试。
答案 0 :(得分:0)
The page is lagging because you're executing sizesList=document.getElementsByClassName(...
continuously. The setTimeout is asynchronous, so it won't do anything.
To poll every 700ms like you expect, you should consider setInterval
:
setInterval(function() {
if(typeof(sizesList) == 'undefined')
sizesList=document.getElementsBy(...
}, 700)