Local or Remote JavaScripts?

Thu, Oct 16, 2008

Technology

In case you haven’t noticed I use jQuery on my blog ( I always had a way of overstating the obvious).  There are plenty of great reasons why I have chosen the jQuery library, and perhaps another great reason has come along…  Google has decided to host the jQuery library in their API library:

“The AJAX Libraries API is a content distribution network and loading architecture for the most popular open source JavaScript libraries.  The AJAX Libraries API provides your applications with stable, reliable, high speed, globally available access to all of the most popular, open source JavaScript libraries.”

So you may be asking yourself, ”hmm… why is this a good thing?” – Well, using Google’s API provides your clients with a fast, resilient, and (most importantly) offloaded source for the jQuery script. Whenever someone needs to download the jQuery script they aren’t using your network bandwidth, there’s probably a closer and faster Google API server. Seems like a win-win for everyone. 

So your convinced and ready to use it, right?  But wait, you need to make some considerations when using this resource. 

To start with here’s the info from the Google API Site:

jQuery
    name: jquery
    versions: 1.2.3, 1.2.6
    load request: google.load("jquery", "1.2.6");
    extras: uncompressed:true, e.g., google.load("jquery", "1.2", {uncompressed:true});
    path: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js
    path(u): http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
    site: http://jquery.com/
    note: 1.2.5 and 1.2.4 are not hosted due to their short and unstable lives in the wild...

So a typical call would be like the following:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

But what happens if the web connection is via HTTPS?  You don’t want that ugly SSL error because of unsecured links.  So how about something like the following:

<script type="text/javascript">
    document.write([
        "\<script src='",
        ("https:" == document.location.protocol) ? "https://" : "http://",
        "ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js' type='text/javascript'>\<\/script>"
    ].join(''));
</script>

Next, you might want to verify that jQuery has actually loaded correctly…  Something like this might do:

<script type="text/javascript">
    if (typeof jQuery != 'undefined') {
       $j = jQuery.noConflict();
    }
</script>

You should now be able to verify that your web browser is pulling the jQuery JavaScript from the Google site. 

What do you think?  Does it make sense to use Google’s API servers?

Comments are closed.