Gazishaheen’s Weblog

creating JavaScript libraries

Posted by: gazishaheen on: March 16, 2009

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!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


  • Mr WordPress: Hi, this is a comment.To delete a comment, just log in, and view the posts' comments, there you will have the option to edit or delete them.

Categories

Follow

Get every new post delivered to your Inbox.