Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

javascript - How to add hundreds of shapes on page without slowing page load

I am trying to add hundreds of little "squares"/shapes on a page using JS. However, whether using SVG or divs, the page load is very slow. Is there a more efficient way to create multiple shapes on a page without slowing down the page load?

Here is an example in JSFiddle, which has both svg and div examples

Here is the 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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of concatenating HTML text to the innerHTML each time, append an <svg> element. Also, you should only query for #test (aka container) once; outside of your loop.

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...