JavaScript_A Beginner's Guide - Using an external JavaScript file - 09/20/2012

来源:互联网 发布:php开源文档管理 编辑:程序博客网 时间:2024/05/16 02:56

The most common way to set off a script is to use the HTML <script> and </script> tags in your document. You can place your script tags in either the head or body section of an HTML document.

Script tags are used to tell the browser where some type of scripting language will begin and end in an HTML document.Besides distinguishing where a script begins and ends for the browser, script tags can also tell the browser which scripting language will be used and define the address for an external JavaScript file.

An external JavaScript file is a text file that contains nothing but JavaScript code, and it is saved with the .js file extension.By calling an external file, you can save the time of coding or copying a long script into each page in which the script is needed. Instead, you can use a single line on each page that points to the JavaScript file with all of the code.

You can call external scripts by adding an src (source) attribute to the opening script tag:

<script type="text/javascript" src="yourfile.js"></script>

This example calls a JavaScript file named yourfile.js from any page on which you place the line.

the browser will cache the external JavaScript file the first time it is loaded, making subsequent Web pages that use the script render faster. 

This is the first line, before the script results.<br />  <script type="text/javascript">    document.write("Yes! I am now a JavaScript coder!");  </script><br />This line comes after the script   <br> tag to insert line breaks

Document is one of JavaScript’s predefined objects, and write() is a predefined method of the document object. The dot puts the object and the method together to make the function work. 

Open a new file in your text editor and insert only the JavaScript code (the document. write() statement) itself. The script tags are not needed in the external JavaScript file. The file should appear like this:  document.write("Yes! I am now a JavaScript coder!"); Save the file as jsfile1.js in your text editor. Creating the HTML Files

<body><script type="text/javascript" src="jsfile1.js"></script><p>This is page 1, and the script works here!</p></body>


Although we used a short script in this example, it should give you an idea of how using an external file could be a great time-saver when you have a large script.

原创粉丝点击