Embedding Scripts


Browser software is dumb in the sense that it thinks everything is HTML. Feed it a Web page, and everything is fine. But feed it a text document or a JavaScript, and the browser tries to interpret it as HTML, and you get something like Figure 12.1. Instead of executing the embedded script, the browser treats it as HTML and displays the code on the page.

Figure 12.1. If you embed a script without enclosing it in script tags, the browser assumes it's HTML and displays it on the page.


To avoid this problem, you have to tell the browser exactly where the script begins and ends. Hence, the script tag. Enclose your script between a pair of script tags, like this:

 <script language="JavaScript">   function doAlert() {     alert("I am a script.");   } </script> 

This way, when the browser translates the HTML, it knows to skip over whatever appears between the script tags.

That's the first step to embedding a script. The second is figuring out where to place the embedded script in the HTML code. The answer depends on what type of script it is. Scripts with repeatable or interactive functionsfunctions that can be called more than once per page or functions that change the appearance of the page after the browser builds itbelong near the top of the HTML code, between the head tags and after the title tag:

 <html>   <head>     <title>Page Title</title>     <script language="JavaScript">       /* The JavaScript goes here. */     </script>   </head>   <body>     <!-- The content of the page goes here. -->   </body> </html> 

Scripts for image rollovers or popup menus fall into this category, as do scripts that verify form input.

However, if you have a script that executes once when the browser initially builds the page, as in the case of custom text or a timestamp, embed the script exactly where you want the results to appear:

 <html>   <head>     <title>Page Title</title>   </head>   <body>     <!-- Insert a dateline at the top of the page. -->     <script language="JavaScript">       /* Dateline script goes here. */     </script>     <!-- The rest of the page goes here. -->   </body> </html> 



Web Design Garage
Web Design Garage
ISBN: 0131481991
EAN: 2147483647
Year: 2006
Pages: 202
Authors: Marc Campbell

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net