views:

68

answers:

2

Hi,

I was wondering if I could do the following:

load a html page and set the backgroung color of the body element dynamically with javascript, in this case with a jquery script. If the page elements are loaded before the js executes, then the body color will be white for a second, and then it changes the color. If the js would be loaded before the rendering of the html then we wouldnt have a body yet to apply the changes right? Or am I wrong? Could you please give me a tip what is the best solution for this? Thanks a lot

greetings

+1  A: 

You can bind an event to be fired when the DOM tree is ready, which will generally be before the page is displayed.

http://docs.jquery.com/Events/ready

I use this for unobtrusive javascript to start changing the page ASAP, so the user doesn't see any changes due to the javascript.

Edit: There is another solution, which isn't ideal, but can work. Have the main div be hidden, so nothing gets displayed, until the DOM tree is finished, and the javascript changes the main div to be visible.

The other option is to put the javascript at the end of the html, and have it immediately set the color, but this is very much a timing solution.

James Black
sorry, but you're wrong: in most cases, the browser will start rendering the page *before* `DOMContentLoaded` (or equivalent hacks) fires; you can even delay the event by an arbitrary amount of time by using chunked transfers (PHP example: add `flush();sleep(42);` before the closing `</body>`)
Christoph
Thats what I did, but that means that the body was loaded already which gives this white background for a second :(
I am used to having tables or images, something that slows down rendering, so I haven't had a situation where the page gets rendered before the DOM tree is finished.
James Black
+1  A: 

In most cases, using DOMContentLoaded (or the equivalent hacks) is sufficient. It's problematic if the parsing of the HTML code is delayed (eg because of server- or clientside computations or a slow connection) or - as in your case - undesired visual effects; I wrote about this problem in regards to chunked transfers some time ago.

You should experience the least time lag by adding script elements to the body directly after the involved elements (see this question as to when this is problematic).

Your example of changing the body's colour would look like this:

<body>
 <script type="text/javascript">
 document.body.style.background = 'green';
 </script>
Christoph