Developer Tips & Tricks - Using the Google Libraries API

January 18, 2012

The Google Libraries API is a content distribution network (CDN) and loading architecture for the most popular, open-source JavaScript libraries. By using this API, you avoid having to host some of the most popular Javascript libraries that you might find yourself needing to use in your Gadgets for our digital signage software.

To use the Google Libraries API, link to the following Javascript file:

<script type="text/javascript" src="https://www.google.com/jsapi?key=INSERT-YOUR-KEY"></script>

Get started with Rise Vision

You can sign up for an API key to pass along as a parameter if you wish, although it is optional. If you decide not to use a key, the <script> tag would simply be:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

Next, you load the libraries that your Gadget requires by calling the google.load()function:

google.load("jquery", "1.7.1");

The first parameter to google.load() is the name of a library. The second parameter is the version number of that library. You can specify either a specific version (e.g. 1.7.1) which will load that exact version, or a truncated version (e.g. 1) which loads the most recent version in that branch. You also need to set google.setOnLoadCallback. This allows you to register a specific handler function to be called once the library has loaded. For example:

google.setOnLoadCallback(function() {
$(function() {
// Do some jQuery.
});
});

Alternatively, you can link to any of the libraries in Google's CDN directly, bypassing the Google Libraries API altogether. You do this using standard <script> tags. This method offers faster loading times. For example, you can load the jQuery library by simply adding the following single line of HTML:

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

My preferred method is to use google.load() with a truncated version number. While this may be slower, it ensures that the most current version of the library will be loaded each time the Gadget is run. With the script tag method, you would have to revisit each tag if you wanted to upgrade to a newer version.

You can visit this link to see a complete list of the libraries that can be loaded from Google's CDN.