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="http://www.google.com/jsapi" 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 %>);
</script>
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.

Comments

dan said…
but what if you don't want google to know that you are using jquery?
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: http://blog.jquery.com/2009/08/20/codejquerycom-redirected-to-google-ajax-apis/.

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.
Good tip! I hadn't thought about limited connectivity. That's a killer.