tags:

views:

56

answers:

3

Will the DOM definitely be ready if I place my jquery code right before the </body> tag?

I have some jquery code and when I put it in the $.ready() function I can see a flash of what the page looks like before the javascript code is run.

However, if I put the code right before the </body> tag then I only see what the page looks like after the javascript is run. I used timers to see the time difference, and the code put before the end of the </body> executed 300ms sooner than the code in $.ready.

EDIT:If the DOM is reliably ready when i call my code before the </body> tag, what is the benefit to putting my code in $.ready, considering that my javascript will execute sooner if I put it before </body>?

+3  A: 
T.J. Crowder
+3  A: 

Yes, the DOM is ready by then, but you still can't be sure that you don't see a flash of the page in it's original state.

If you have something that shouldn't be visible in the page from start, you can use CSS in a style sheet to hide it initially, instead of hiding it using jQuery. That way you will be sure that there will not be a flash of the elements before you have a chance to hide them.

Guffa
+1  A: 

I'm 99% sure that it will work on the DOM that is in existance before the <script> tag. This means that if it's before </body>, it will work.

I'd be curious to see if it ever worked on something after the closing </script>. Like maybe the internet loaded the page faster than the processor could begin the JavaScript code... I doubt it thought because if you do document.write, it should be at the same point where the <script></script> is at.

bradlis7
@Yes, you are right about document.write; the code after the script tag will not be parsed until the script completes even if the code has arrived, as the script might write something to the page which will have to be parsed first.
Guffa
@bradlis7: *"I'd be curious to see if it ever worked on something after the closing `</script>`..."* No, not unless you use `defer` or `async` (http://www.w3.org/TR/html5/scripting-1.html#attr-script-async) and the browser supports it. All DOM rendering comes to a screeching halt until the JavaScript has been (downloaded and) run, for exactly the reason you mention: `document.write`
T.J. Crowder
Thanks, both of you. That's the best way for a browser to handle it, as HTML, with the exception of loading multiple images, is meant to be one processor thread.
bradlis7