问题描述
我正在尝试使用 JS 在页面上添加数百个小“正方形”/形状。但是无论是使用SVG还是div,页面加载都很慢。有没有更有效的方法可以在不减慢页面加载速度的情况下在页面上创建多个形状?
这是JS:
var num = 700
for (i=0; i < num; i++){
let el = '<div class="els"></div>';
let elSVG = '<svg class="els"></svg>';
let container = document.getElementById("test");
container.innerHTML = container.innerHTML + elSVG
}
解决方法
不是每次都将 HTML 文本连接到 innerHTML
,append
是一个 <svg>
元素。此外,您应该只查询一次 #test
(又名 container
);在你的循环之外。
const
container = document.getElementById('test'),num = 700;
const createSvg = () => {
const svg = document.createElement('SVG');
svg.classList.add('els');
return svg;
};
for (let i = 0; i < num; i++) {
container.append(createSvg());
}
body {
background-color: #111
}
.els {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 16px;
background-color: #EEE;
}
<div id="test"></div>
更新:正如 Danny 提到的,您可以将所有 SVG 元素附加到 DocumentFragment
中,然后将所述片段附加到容器中。
const fragment = new DocumentFragment();
for (let i = 0; i < num; i++) {
fragment.append(createSvg());
}
container.append(fragment);
,
您总是会减慢页面加载速度,不可能在不减慢速度的情况下完成。
但您可以聪明地创建内容。
-
innerHTML 和 append 会在每次插入时触发浏览器重排/重绘
-
使用 DocumentFragment 构建内存中的所有 HTML,然后注入 DocumentFragment 一次。
https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
-
您可能还想查看
<template>
,
克隆模板仅解析HTML一次https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template
<style>
body {
background-color: black
}
.els {
height: 2px;
width: 1px;
background-color: white;
margin-right: 1px;
display: inline-block;
}
</style>
<div id="$Container">
</div>
<script>
console.time();
let fragment = new DocumentFragment();
let num = 4 * 700;
for (i = 0; i < num; i++) {
let el = document.createElement("div");
el.classList.add("els");
el.appendChild(document.createElement("svg"))
.classList.add("els");
fragment.append(el);
}
$Container.append(fragment);
console.timeEnd();
</script>