2

Jquery has a ready method:

$(document).ready(function(){
   // my code
})

It will execute my code when dom is ready.

I have a question, if I put all my scripts after </body>, e.g.

<html>
    <body>
       // all kinds of html tags
    </body>
    <script src="/path/to/jquery.js"></script>
    <script src="/path/to/all-javascript-compressed-in-one-file.js"></script>
</html>

Do I still need to write $(document).ready()? Is the dom already ready after </body>?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • And if it is `no`, is it `no` on all kinds of browsers? – Freewind Nov 01 '12 at 14:00
  • The thing is, you want your script to be function code anyway, so you want a function wrapper, and `jQuery(function ( $ ) { ... });` is a convenient way to achieve that. – Šime Vidas Nov 01 '12 at 14:00

2 Answers2

4

Usually, the scripts are added just before </body>, not after it – the HTML won't validate otherwise; no content can appear outside <head>, or <body>, as noted by Šime Vidas on his comment.

That being said, technically the DOM is not considered ready yet at that point (as the browser is still parsing the <body>), but already contains all elements from the body. Thus, it's safe to skip $(document).ready().

Doing that will execute your initialization scripts earlier, since there is some delay before the actual DOMContentLoaded event is fired. That means a faster page load, and a better user experience.

You might be interested in this related discussion about forcing the jQuery ready event.

Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • I read some where that recommends putting the script last (for faster page load probably) – alfred Nov 01 '12 at 13:56
  • @alfred - yes, put them last, but usually, as pointed out, they are placed immediately before the closing body tag, not after it. – Adam Jenkins Nov 01 '12 at 13:58
  • That's just how HTML is defined. No content can appear outside ``, or ``. – Šime Vidas Nov 01 '12 at 14:04
  • @myself -personally I favor to put the scripts first, inside the head section. this helps prevent some errors when calling to missing functions – alfred Nov 01 '12 at 14:11
3

In a word, no. The dom is considered "ready" when the dom tree is available, if your javascript is the last thing on the page, then everything before it is "ready", as web pages are "loaded" from the top down.

Randy Hall
  • 7,716
  • 16
  • 73
  • 151