Categories:
Partners

General syntax for creating JavaScript libraries

All JavaScript libraries consists of two parts 1) The library itself, which is simply a file, saved with the extension .js, that contains some JavaScript code, and 2) A <script> tag, defined on the page(s) that uses the library, used to "connect" to 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>
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). Type out everything above, except 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">
</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>

Now, as mentioned in the beginning of this tutorial, NS 2 and IE 3 do not support external JavaScript libraries. So what do you think will happen when these browsers sees the above reference to a library? Absolutely nothing! To them, its just a no-good script that contains no code inside of it, which works to our advantage (degrades well).

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!