Linking JS and HTML Files


Some web authors prefer not to mix JavaScript and HTML code in one document. For tidiness and efficient authoring, they move the JavaScript code to an external document, named with the .js file extension, and link that file to the HTML file. When a JS file is linked to an HTML document, the JavaScript interpreter treats the two files as one. Any JavaScript functions in the JS file can be called on from the HTML file and executed. To link an HTML file to a JS file, use the <script> tag with the following syntax and with no contents:

 <script language="JavaScript" src="MyScripts.js"></syntax> 

Listing A.5 shows an HTML file with embedded JavaScript functions. Listing A.6 and

Listing A.7 show the same file with JavaScript code removed to a linked JS file.

Listing A.5 Contents of the MyDoc.html File with All JavaScript Code Contained in the Document (Script Tag Shown in Bold)
 <html>  <head>  <title>JavaScript Test</title>  <script language="JavaScript">   function testMe() {   alert("Hello, world!");   }   </script>  </head>  <body>  <a href="#" onClick="testMe()">Click here</a>  </body>  </html> 
Listing A.6 Contents of the MyDoc.html File with JavaScript Function Removed to a Linked JS File (Script Tag Shown in Bold)
 <html>  <head>  <title>JavaScript Test</title>  <script language="JavaScript" src="MyScripts.js">   </script>  </head>  <body>  <a href="#" onClick="testMe()">Click here</a>  </body>  </html> 
Listing A.7 Contents of the MyScripts.js file
 function testMe() {  alert("Hello, world!");  } 


Dreamweaver MX Extensions
Dreamweaver MX Extensions
ISBN: 0735711828
EAN: 2147483647
Year: 2001
Pages: 141
Authors: Laura Gutman

Similar book on Amazon

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