cascading-style cascading-style - 10 days ago 5
CSS Question

Hide body until it finishes loading

I created this code so my page would be hidden until it finishes loading. But my code doesn't work as I expected. I expected this to hide the

BODY
until the
OnLoad
event was triggered.
However, instead, it just stays hidden.

Any help would be appreciated, if there is maybe another, better method of hiding the
BODY
until it finishes loading, or what's wrong with this one.




Here's what I've tried so far:


function unveil() {
var thebod = document.getElementById("testbody");
thebod.STYLE = "display: block;"
}

<HTML>

<HEAD>
<TITLE>HELLO</TITLE>
</HEAD>

<BODY ID="testbody" ONLOAD="unveil();" STYLE="display: none;">
<div align="CENTER">
HELLO WORLD!
</div>
</BODY>

</HTML>




Answer

The DOMContentLoaded event of the window object can do this. But, don't hide the body, hide a wrapper instead. And, when you set the style, make sure to set the style of a CSS property, not the style object itself.

window.addEventListener("DOMContentLoaded", function(){
  document.getElementById("wrapper").style.display = "block";
});
#wrapper { text-align:center; display:none;}
<HTML>

<HEAD>
  <TITLE>HELLO</TITLE>
</HEAD>

<BODY>
  <div id="wrapper">
    HELLO WORLD!
    
    <!-- The following is only added to create a delay in the 
         parsing of the document -->
    <script>
      for(var i = 0; i < 100000000; ++i){ var x = i / 3.14; }
    </script>  
  </div>
</BODY>

</HTML>

Comments