...

View Full Version : placement of js functions on the page



elyod_72
08-28-2007, 12:06 AM
This may be a silly question, but do javascript functions have to be placed in the <head> of the html document? Can they be in the body instead?

Philip M
08-28-2007, 09:02 AM
This may be a silly question, but do javascript functions have to be placed in the <head> of the html document? Can they be in the body instead?

A function acts as a definition for what to run when that function is called. In most cases you will want to pre-load the function code so that it is available as and when needed by the Javascript code you include in your web page. This means palcing the function code into the <head>. You can of course place the functions in the <body> if you prefer. The important thing is that the function is defined before you call it from your program.

It is very common to call a script via a <body onload...> statement. In general scripts if placed in the <body> appear right after the <body> tag, but in some cases it may be desirable to place them right at the end, e.g. scripts that pre-load images used on other pages.

Another point to consider when deciding whether to place your Javascript in the head or body section of the page is that if your code writes to the web page or affects the web page in any way then the statements to do that processing may only be included in the <body> section of the page or in functions within the <head> section of the page which are called from within the <body> of the page.

Hope this helps.

Kor
08-28-2007, 01:29 PM
So, by short, javascript functions may be placed in head or in body as well; technically it does not matter.

Philip M
08-28-2007, 01:42 PM
So, by short, javascript functions may be placed in head or in body as well; technically it does not matter.

Sorry, Kor. I don't agree.

"Another point to consider when deciding whether to place your Javascript in the head or body section of the page is that if your code writes to the web page or affects the web page in any way then the statements to do that processing may only be included in the <body> section of the page or in functions within the <head> section of the page which are called from within the <body> of the page."

For example, the code I supplied to canadianjameson in
http://www.codingforums.com/showthread.php?t=122436
will not work in the <head> as it includes document.write.

Kor
08-28-2007, 01:56 PM
That code (and any other code) should simply not use document.write, as it is not a dynamic method. I always use DOM methods to create elements on the page, thus I may place my codes anywhere I like. Usually I prefere the head, but there are cases (includes) where I put them in the body.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum