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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值