Is there a correct place to put javascript within a html file?

T

Thomas 'PointedEars' Lahn

mark4asp said:
[...] 2. If code requires access to DOM elements, it should not be
called before they might exist and should not error if it is.

How you achieve the above is up to you, but the general way is to
achieve the first is to load scripts containing general functions in
the head.

There are a variety of ways to achieve the second - inserting functions
intended to be run when the DOM is ready rather than onload into a
script element just before the closing body tag is one. There are
others, such as using a general "DOM ready" function or waiting for
the load event to occur. [...]

[...] In future, I will generally place my script just before the </body>
tag - unless there is a reason not to.

The reason is that only when then the `load' event occurs, all DOM objects
objects can be considered to be accessible. The `body' element has the
`onload' intrinsic event handler attribute to handle that event.
Even then it will be a rare bit of code that is needed in the head
element.

It won't, but it will be more error-prone.
If all my javascript is positioned just before the </body> then the
various html elements must be rendered or in the process of being
rendered before and javascript can run.
Wrong.

I don't have much javascript executing on window.onload but I suppose I
could put code in there to check for the existence of an object before I
use it, set and interval and recurse back?

Yes, but using the `onload' attribute of the `body' element for that would
be wiser.
I'm trying to follow Steven Sounders advice from "High Performance Web
Sites"

Do I have to know him?


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,125
Latest member
VinayKumar Nevatia_
Top