views:

44

answers:

1

It is said that Javascript code should be all placed at the end of HTML file, so that the page content is shown first, for the user to see something (so that the user is satisfied to see something instead of waiting another 12 seconds, for example).

But to better encapsulation of the HTML and match Javascript code, such as an "Image Carousel", then usually the HTML and Javascript is placed in one single file, so there are Javascript code blocks all intermixed with HTML code throughout the final HTML file.

But what if all these Javascript code blocks use jQuery's $(document).ready(function() { ... }) to perform the task, then won't the page display be very fast as well? I think not as fast as when the Javascript is actually placed at the end of the HTML file, but close enough, because it merely adds a function to the ready event queue.

+1  A: 

I think the point is to place the js at the bottom of the page (usually just inside the closing </body> tag) so that the content of the page is displayed while the js is downloading.

If you have your jQuery code spread out throughout the HTML in separate .ready() calls, then no matter what, it won't run until the <body> has fully loaded. So the question would be how much javascript do you have in the HTML?

If there's quite a bit, then it will slow down the display of any content that comes after each script. If it is a relatively small amount of code, then it won't likely make much noticeable difference.

If it is really important to you to have the page's content displayed as soon as possible, then place all scripts after the content.

I personally wouldn't mix javascript with HTML just for the sake of association. You could have unexpected results if you start removing/appending content that happens to include a script. I'd rather use appropriately named classes and IDs, as well as lots of code comments.

Also keep in mind that those .ready() calls won't work until jQuery has loaded, which would mean that it would need to be at the top of the page, or at least before your first call.

So again it gets back to the question of which is more important to you. If you want the content visible as quickly as possible, place all js at the bottom. If you want your method of intermixing js and HTML, you'll have some delay in displaying the page.

patrick dw