How to Set Body Background Color in JavaScript before page load.

I recently answered a question at StackOverflow about how to change the background color of the BODY element of a web page, before the page was loaded… using JavaScript.

Instead of relying on event handlers, I went with one of the earliest (and least used these days) methods in javascript:

document.write

Yes, document.write. It’s one of the earliest ways of rendering HTML onto a web page using JavaScript, and I had tons of fun with it when I was 14. Anyway, here’s the code…

<!doctype html>
<html>
   <head>
      <title>Background Change</title>
      <meta charset="UTF-8">
      <style type="text/css">
      body {
           background-color: #FFFFFF;
      }
      </style>
      
      (function(){
           var color = "#000000";
                  document.write("<style type=\"text\/css\">" + 
                   "body{background-color: " + color + ";}</style>");
            }
      }());
      
    </head>
    <body>
....
    </body>
</html>

In the above example, we created an anonymous function, then simply wrote in a <style> tag with our changes to CSS.

That’s it!

Don’t forget, complexity can kill your chance of success.