我在使用 jQuery 时遇到了一些性能问题。因此,我想用 JS 而不是 jQuery 来尝试我的循环,长度为 7000。因为我读到,jQuery 的性能一直很差。
我尝试将我的 jQuery 选择器转换为 JS,但它仍然无法正常工作:
来自:
var i;
for (i = 0; i < e.detail.length; i++){
$("iframe").contents().find(".timeline-node[title='" + i + "']").css("background-image", "url( \"imgs/" + e.detail[i] + ".png \") ");
}
到:
var i;
for (i = 0; i < e.detail.length; i++){
document.getElementById('#iframe').querySelector("[title=\"" + i + "\"]").css("background-image", "url( \"imgs/quality_3/" + e.detail[i] + ".png \") ");
}
我的新代码的错误是:无法读取 HTMLDocument 中 null 的属性“querySelector”。
我认为 JS 无法通过 attr 找到我的标题。我。但是我的 jQuery 代码运行良好,但需要 80 秒。为 7000 个索引执行此操作。
只查询一次iframe
var i, iframe = document.querySelector('iframe').contentWindow.document;
for (i = 0; i < e.detail.length; i++){
iframe.querySelector("[title=\"" + i + "\"]").style.backgroundImage = "url( \"imgs/quality_3/" + e.detail[i] + ".png \") ";
}
您可以尝试只使用一个查询并过滤结果
document.querySelector("iframe").contentWindow.document.querySelectorAll("[title]").forEach(function (elm) {
var id = +elm.getAttribute("title");
if (id < e.detail.length) {
elm.style.backgroundImage = "url( \"imgs/quality_3/" + e.detail[id] + ".png \") ";
}
});
多 iframe 版本
document.querySelectorAll("iframe").forEach(function (iframe) {
iframe.contentWindow.document.querySelectorAll("[title]").forEach(function (elm) {
var id = +elm.getAttribute("title");
if (id < e.detail.length) {
elm.style.backgroundImage = "url( \"imgs/quality_3/" + e.detail[id] + ".png \") ";
}
})
});
性能比较
console.time("loop");
var i;
for(var a = 0; a < 10; a++) {
for (i = 0; i < 20; i++){
document.querySelector("[title=\"" + i + "\"]");
}
}
console.timeEnd("loop")
console.time("singleQuery");
var i;
for(var a = 0; a < 10; a++) {
document.querySelectorAll("[title]").forEach(function(elm) {
if(+elm.getAttribute("title") < 20) {
// change background
}
});
}
console.timeEnd("singleQuery")
<p title="0"></p>
<p title="1"></p>
<p title="2"></p>
<p title="3"></p>
<p title="4"></p>
<p title="5"></p>
<p title="6"></p>
<p title="7"></p>
<p title="8"></p>
<p title="9"></p>
<p title="10"></p>
<p title="11"></p>
<p title="12"></p>
<p title="13"></p>
<p title="14"></p>
<p title="15"></p>
<p title="16"></p>
<p title="17"></p>
<p title="18"></p>
<p title="19"></p>