Forum Moderators: open

Message Too Old, No Replies

Java script placement on a page

only in the <head>?

         

fmaz

4:13 pm on Jul 6, 2004 (gmt 0)

10+ Year Member



Hi, I'm coding my web page in PHP so I auto-include the header and the footer for each page.

Some pages require javascript... do it create some thing like:

<html>
<head>
...
</head>
<body>
<script>...</script>
...
</body>
</html>

I can't really place the script in the <head> because I should create a specific page detection in the header.php file and it would be conplicated and not really clean.

Now I know this method work, but, I'm trying to code in XHTML STRIC... so I wanted to know if it was "legal" to put java script inside the <body> ...

:-\

createErrorMsg

8:27 pm on Jul 6, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



javaScript in the <body> is read and executed by the browser as it reaches the <script> tag while loading the page. If your JS is a function that will be called based on user action (onclick, onmouseover, onfocus, etc) or a function that runs after the page is finished loading (onload), it needs to be in the <head> tag.

Your best bet is to stuff it all into an external .js file (simple text saved with a .js extension) and add...
<script type="text/javascript" src="YOURFILE.js"></script>
...to the <head>.

This could be included in the head of pages that don't need the JS and will not affect anything until and unless the script functions are called.

Bernard Marx

8:20 am on Jul 7, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The position of a script block has no bearing on whether or not the functions it defines can be used after the page has loaded. If statements are 'inline', that is to say they will be activated immediatel, and they write anything, then the content will be written where it lies, after the scriipt tag.

As to your question about XHTML strictness, I don't know, but I guess not. It certainly is easier to use an external link.

Span

8:32 am on Jul 7, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It's legal to put JS in xhtml if you don't use <!-- comment --> tags and tell XML parsers the code between the script tags is CDATA and should be ignored.
If your script contains ]], put a space between them.

<script type="text/javascript">//<![CDATA[

//]]></script>

fmaz

1:59 pm on Jul 7, 2004 (gmt 0)

10+ Year Member



ok...

so if I do this, it will NOT work?:

<html>
<head>
</head>
<body>
<script type="text/script" language="javascript1.2">
//<![CDATA[
function ShowMSG() {
Alert("I got clicked!");
}
//]]>
</script>

Welcome<br />
<a href="#" onClick="ShowMSG()">CLICK ME</a>
</body>
</html>

Bernard Marx

5:17 pm on Jul 7, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



alert :)

Span

7:17 pm on Jul 7, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just use: <script type="text/javascript"> for valid xhtm1.0 strict