views:

485

answers:

3

The question pretty much already says everything.

I'm starting to add some features to my weekend project. It's a small app for me and a couple of friends, as we're exchange students it's kinda useful for us.

But the thing is the following, I'm doing this in php and structuring everything with includes so i can get the code separated. Some of these pieces of code are dependent on javascripts snipets, so how bad is it to put a javascript in the middle of the body? Or should i just make double includes so the javascript stays in the header?

+2  A: 

It is perfectly fine to place Javascript into the body. There is even such a thing as "inline" Javascript. Just don't overdo it. If you can package your scripts into a separate file (which is not always possible), it will make your code more maintainable.

cdonner
A: 

There are good an bad reasons to do it.

GOOD) If the script is not critical to the construction of your page DOM, it is good to do it as late as possible as Jim Puls suggests, usually at the very bottom of the page in the root BODY node. This is good because it allows the XHTML to render immediately, creating a psychological effect that the page "loads faster." In reality, it is loading at the same speed except that the browser isn't spending CPU cycles downloading, interpreting, and running the JS while the user stares at a white browser window.

BAD) Script tags are typically downloaded an interpreted in the order which they are enclosed. This means that you need to manage carefully the order in which they are included. Also, because they load serially (one at a time), you pay a high cost for each additional file you reference because the browser has to establish connection, check cache, download, etc. Tricks such as IE's "DEFFER" are not standard. For this reason, I would highly recommend packing your javascript into a single file when you go from development to production so that users do not have to make multiple connections in serial. Also make sure you have gzip compression turned on.

GOOD) There is a way to lazy-load scripts using AJAX -- you call your sever asking for the JS, and raise an event when the file is loaded. You can then call eval on it (or some safer variant) which brings its symbols into scope. This allows parallel downloads of script.

GOOD & BAD) In IE, you must avoid manipulating the DOM tree before the DOM has fully loaded. Look up the 'dom:loaded' event for this.

thesmart