Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optimized solution for filling entire page with DIVs

I want to have a webpage whose entire viewable area is filled with divs. I am currently using the following code:

var wh= window.innerHeight;
var ww= window.innerWidth;
var area= wh * ww;
i= 1;
while(area > 0) {
document.getElementById("map").innerHTML+= "<div class='map-box' id='box" + i + "'></div>";
area-= 20 * 20;
i+=1; 
}
.map-box {width: 20px; height: 20px; border-color: grey; border-width: 1px; border-style: solid; display: inline-block; margin: 0; padding: 0;}
<body>
<div id='map'></div>
</body>

If you try to use this code is your browser, you will see that there are two flaws in this:

  • First, it creates too many extra divs which go outside the viewable screen.
  • Second, this code is also somewhat slow.

Can someone here help me address both of these flaws and also optimize this code for faster performance?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Instead of accessing dom element’s inner html on each loop iteration – do it once after the loop with "prepared" data to set there

  const wh = window.innerHeight;
  const ww = window.innerWidth;
  let area = wh * ww;
  i = 1;
  const ms = Date.now();
  const divs = [];
  while (area > 0) {
    divs.push("<div class='map-box' id='box" + i + "'></div>");
    area -= 20 * 20;
    i += 1;
  }
  document.getElementById("map").innerHTML = divs.join("");
  console.log("done fast", Date.now() - ms);

js fiddle with comparison https://jsfiddle.net/aL7zqwy9/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading