• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 16. Applied JavaScript > Using an External .js File

Using an External .js File

If you have common code throughout your entire Web site, you don't need to add it to every Web page. Instead, you can create an external JavaScript file and have the pages just refer to that file, which can save you a lot of code for each page. This external file is called a .js file, because whatever it's called, the file name should end with the suffix .js. Individual pages call the .js file simply by adding a new attribute, src, to the script tag. Scripts 16.1, 16.2, 16.3, 16.4, and 16.5 demonstrate how this is done.

To use an external .js file

  • <script src="external.js"
    → language="Javascript"
    → type="text/javascript">
    

    Adding the src attribute to the script tag causes browsers that support JavaScript 1.1 and later to look for that file. The resulting Web pages will look just as though the scripts were in their usual place inside the page's script tags, when really the script resides in the external .js file. The result of this technique is shown in Figures 16.1 and 16.2.

    Figure 16.1. The rollover code isn't in this file, but rollovers still work on this page…


    Figure 16.2. And on this page too, because they both call the same external file.



PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint