Java Reference
In-Depth Information
created a file called MyCommonFunctions.js to which you want to link, and the file is in the same
directory as your web page. The <script/> element would look like this:
<script src="MyCommonFunctions.js"></script>
The web browser will read this code and include the file contents as part of your web page. When
linking to external files, you must not put any code within the opening and closing <script> tags;
for example, the following would be invalid:
<script src="MyCommonFunctions.js">
var myVariable;
if ( myVariable == 1 ) {
// do something
}
</script>
It's important to note that an opening <script> tag must be accompanied by a closing
</script> tag. You cannot use the self‐closing syntax found in XML. Therefore, the following
is invalid:
<script src="MyCommonFunctions.js" />
Generally, you use the <script/> element to load local files (those on the same computer as the web
page itself). However, you can load external files from a web server by specifying the web address of
the file. For example, if your file was called MyCommonFunctions.js and was loaded on a web server
with the domain name www.mysite.com , the <script/> element would look like this:
<script src=" http://www.mysite.com/MyCommonFunctions.js"></sc ript>
Linking to an external file is common when incorporating well‐known JavaScript libraries into
a web page. The servers hosting these libraries are referred to as Content Delivery Networks , or
CDNs. CDNs are relatively safe, but beware of linking to external files if they are controlled by
other people. It would give those people the ability to control and change your web page, so you
need to be very sure you trust them!
advantages of using an external file
The biggest advantage of external files is code reuse. Say you write a complex bit of JavaScript that
performs a general function you might need in lots of pages. If you include the code inline (within
the web page rather than via an external file), you need to cut and paste the code into each web page
that uses it. This is fine as long as you never need to change the code, but the reality is you probably
will need to change or improve the code at some point. If you've cut and pasted the code to 30
different web pages, you'll need to update it in 30 different places. Quite a headache! By using one
external file and including it in all the pages that need it, you need to update the code only once and
all the 30 pages are updated instantly. So much easier!
Another advantage of using external files is that the browser will cache them, much as it does with
images shared between pages. If your files are large, this could save download time and also reduce
bandwidth usage.
 
Search WWH ::




Custom Search