NYCPHP Meetup

NYPHP.org

[nycphp-talk] JavaScript just above form in body?

John Campbell jcampbell1 at gmail.com
Wed Feb 6 14:30:59 EST 2008


On Feb 6, 2008 2:06 PM, Michael B Allen <ioplex at gmail.com> wrote:
> Is it considered bad practice to emit scripts within the body of a
> page such as immediately preceeding the form that uses it? It seems to
> work fine but from looking at some random sites I have yet to see an
> example of this. Logically it makes sense to put the JavaScript close
> to where it will be used no?

The standards nazis will tell you to put scripts in the head.  The
performance freaks will tell you to put your scripts as the last
element in the body.  Putting javascript in the middle of the page, is
bad practice but can simplify development.  So where you put scripts
is up to you... I prefer putting all scripts as the last element in
the body because performance is more important to me than standards
compliance, but I'm not afraid to put them in the middle or inline to
get things done faster.

Just don't do this:
<script>
var form_elem = document.getElementById('myform');
</script>
<form id="myform" ...>
...
</form>

The problem with the above code, is that the script searches for an id
that doesn't exist when the script is run.  It may work in some
browsers, but it will be terrible/buggy code.

I highly recommend using a js library with a good onLoad event
replacement (my favorite is jQuery).  The standard default onload
event sucks because it waits for all images to be downloaded rather
than being a "DOMContentReady" event.

Regards,
John C.



More information about the talk mailing list