Javascript: Best practice to linking external JS library

The best practice to link your html to popular Javascript libraries like jQuery, Dojo, mooTools is to use content delivery network.

Google CDN is a popular choice found at http://code.google.com/apis/libraries/devguide.html.  Just choose the Library you need and grab the link.

To add the library to your page replace what you normally do:

<script src="jquery-1.6.1.min.js"></script>

with:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

It would be better to leave out the “https:” so that your page will use either “https:” or “http” depending on the type of request the page is making.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

The benefits of using CDN over hosting your own is that the browser will download the file in parallel with other js files if they are hosted on a different url. Also the file will be cached if the user has downloaded that file from visiting a different website.

There are other CDNs available including microsoft, but with google, you can use

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

just 1.6 in the path version name and you will get the latest in the 1.6x series. Or better yet, just “1” and it will always grab the latest before “2.x.x”

Author: mark

Creative technologist

1 thought on “Javascript: Best practice to linking external JS library”

  1. I worked on a site which used Google’s CDN for the jQuery libraries; their tech people didn’t like the idea and wanted all of the files to be hosted locally, “in case Google was inaccessible”.

    Perhaps they had a point, but the likelihood of their own server being down seemed slightly more probable. =)

    Unfortunately, you can’t argue with (or kill) clients.

Leave a Reply

Your email address will not be published. Required fields are marked *