Creating and referencing external JavaScript libraries
Most "mainstream" programming languages such as C or Java support "code libraries", where a programmer can save a commonly used piece of code as a library file and reference it from the main program. Well, JavaScript supports external libraries too, in the form of the .js file.
Syntax for creating JavaScript libraries
All JavaScript libraries consists of two parts:
-
The external JavaScript itself, which is simply a text file with the containing JavaScript code, saved as a .js file.
-
A <script> tag referencing the external JavaScript file and defined on the page(s) that uses the library.
For the sake of our discussion, let's pretend you've just created a fabulous code that writes out today's date:
<script type="text/javascript"> function todaydate(){ var today_date= new Date() var myyear=today_date.getYear() var mymonth=today_date.getMonth()+1 var mytoday=today_date.getDate() document.write(myyear+"/"+mymonth+"/"+mytoday) } </script>
Using the above code, lets create a library out of it, so multiple pages can all display a nice date without having to physically include the above code on that page.
Step 1: Open up your text editor (such as notepad), type out the above code, and save it as an individual file with the extension .js (ie: displaydate.js). An external library should include the entire script, minus the surrounding script tags.
Step 2: On all pages that use the above library, create a reference to it by using the below code. It consist of a <script> tag with the optional src property included inside:
<script src="displaydate.js" type="text/javascript"> </script>
By including the above reference, your browser will now download the code stored inside displaydate.js, and run it as if the code was physically typed onto the page. The library file does not have to be stored in the same directory as the page using it. In fact, you can even reference a library that's on a distant domain!
<script src="http://www.yahoo.com/displaydate.js"> </script>
While the biggest reason for using JavaScript libraries is obvious (allows you to easily distribute one code for use on many pages), a secondary reason is not. A JavaScript library, when used on multiple pages, is actually more efficient than directly embedding the code inside the library on each page. Once the browser encounters the library the first time around, it saves the containing code in cache. Subsequent requests for the library on other pages will result in the library being loaded from cache, or the speed demon!