Monday, August 24, 2009

Rails: Using jQuery via Google's AJAX Libraries API

Adding jQuery to your project via Google's AJAX Libraries API is a piece of cake! I just updated my application layout to include:
<script src="" type="text/javascript"></script>
<script type="text/javascript">
<% extras = RAILS_ENV == "development" ? "{ uncompressed: true }": "{}" %>
google.load("jquery", "1.3.2", <%= extras %>);
google.load("jqueryui", "1.7.2", <%= extras %>);
That code loads jquery and jqueryui. I don't have to keep them on my server. I don't have to cache them. It uses the compressed version for production and the uncompressed version in development. Best of all, the user very well might already have that file cached in their browser.


dan said...

but what if you don't want google to know that you are using jquery?

Shannon -jj Behrens said...

To some degree, it's impossible. As soon as you're live, the entire world will know that you use jQuery because they'll see it in the HTML source.

It's interesting to note that jQuery is no longer hosting their own copies of the library. Even they tell you to use Google:

Happy Hacking!

Varikin said...

I have been doing this for a while and is very nice. The one issue is I don't like using that for development. So in Django I have in my base template:

{% if debug %}
local jquery
{% else %}
google jqury
{% endif %}

This is nice for debugging and limited connectivity when developing.

Shannon -jj Behrens said...

Good tip! I hadn't thought about limited connectivity. That's a killer.