All too often, I find code similar to this when inspecting the source for public websites that use jQuery:
If you’re doing this on a public facing website, you are doing it wrong.
Instead, I urge you to use the Google HostedLibraries content delivery network to serve jQuery to your users directly from Google’s network of datacenters. Doing so has several advantages over hosting jQuery on your server(s): decreased latency, increased parallelism, and better caching.
In this post, I will expand upon those three benefits of Google’s CDN and show you a couple examples of how you can make use of the service.
A CDN — short for Content Delivery Network — distributes your static content across servers in various, diverse physical locations. When a user’s browser resolves the URL for these files, their download will automatically target the closest available server in the network.
In the case of Google’s AJAX Libraries CDN, what this means is that any users not physically near your server will be able to download jQuery faster than if you force them to download it from your arbitrarily located server.
There are a handful of CDN services comparable to Google’s, but it’s hard to beat the price of free! This benefit alone could decide the issue, but there’s even more.
To avoid needlessly overloading servers, browsers limit the number of connections that can be made simultaneously. Depending on which browser, this limit may be as low as two connections per hostname.
Using the Google AJAX Libraries CDN eliminates one request to your site, allowing more of your local content to downloaded in parallel. It doesn’t make a gigantic difference for users with a six concurrent connection browser, but for those still running a browser that only allows two, the difference is noticeable.
Potentially the greatest benefit of using the Google AJAX Libraries CDN is that your users may not need to download jQuery at all.
No matter how well optimized your site is, if you’re hosting jQuery locally then your users must download it at least once. Each of your users probably already has dozens of identical copies of jQuery in their browser’s cache, but those copies of jQuery are ignored when they visit your site.
However, when a browser sees references to CDN-hosted copies of jQuery, it understands that all of those references do refer to the exact same file. With all of these CDN references point to exactly the same URLs, the browser can trust that those files truly are identical and won’t waste time re-requesting the file if it’s already cached. Thus, the browser is able to use a single copy that’s cached on-disk, regardless of which site the CDN references appear on.
This creates a potent “cross-site caching” effect which all sites using the CDN benefit from. Since Google’s CDN serves the file with headers that attempt to cache the file for up to one year, this effect truly has amazing potential. With many thousands of the most trafficked sites on the Internet already using the Google CDN to serve jQuery, it’s quite possible that many of your users will never make a single HTTP request for jQuery when they visit sites using the CDN.
Even if someone visits hundreds of sites using the same Google hosted version of jQuery, they will only need download it once!
Note: At the time I originally wrote this, Google used to recommend this loader approach, but no longer does. I’m leaving this section of the post intact, but you can skip to the next section unless you’re planning on time traveling to 2008 someday.
By now, you’re probably convinced that the Google AJAX Libraries CDN is the way to go for your public facing sites that use jQuery. So, let me show you how you can put it to use.
Of the two methods available, this option is the one that Google recommends:
The google.load() approach offers the most functionality and performance.
// Place init code here instead of $(document).ready()
While there’s nothing wrong with this, and it is definitely an improvement over hosting jQuery locally, I don’t agree that it offers the best performance.
As you can see, loading, parsing, and executing jsapi delays the actual jQuery request. Not usually by a very large amount, but it’s an unnecessary delay. Tenths of a second may not seem significant, but they add up very quickly.
Worse, you cannot reliably use a $(document).ready() handler in conjunction with this load method. The setOnLoadCallback() handler is a requirement.
Back to basics
In the face of those drawbacks to the google.load() method, I’d suggest using a good ‘ol fashioned <script> declaration. Google does support this method as well.
// This is more like it!
Not only does this method avoid the jsapi delay, but it also eliminates three unnecessary HTTP requests. I prefer and recommend this method.
HTTPS all the things
Note that the script reference above uses the HTTPS protocol. For years, the examples on this page used a protocol-relative reference, beginning with just
// instead of
https://, and this section of the post described how that was not a typo and was actually a valid URL.
I no longer recommend that approach.
You should always use the HTTPS jQuery CDN reference, even if you’re including jQuery on a page that is itself being served via unencrypted HTTP. This greatly reduces the chances of someone tampering with the contents of the jQuery script between Google’s CDN servers and your users’ browsers. The overhead is minimal and all of the three benefits that I described earlier are still applicable when using the encrypted transport.
WordPress – If you’re using WordPress and want to take advantage of the Google CDN throughout your WordPress site without manually editing themes, plugins, etc, check out Jason Penney‘s Use Google Libraries plugin.
HTML5 Boilerplate – H5BP is a web site skeleton that provides a great starting point for building a modern site. As part of that, it uses a reference to jQuery on the Google CDN (and an automatic fallback to a local copy for users that aren’t able to load jQuery from the CDN for some reason).
According to a recent study, Google will consume 16.5% of all consumer Internet capacity in the United States during 2008. I think it’s fair to say that they know how to efficiently serve up some content.
What do you think? Are you using the Google AJAX Libraries CDN on your sites? Can you think of a scenario where the google.load() method would perform better than simple <script> declaration?
149 Mentions Elsewhere
- Host jQuery at Google (with Intellisense support)
- Dew Drop - December 10, 2008 | Alvin Ashcraft's Morning Dew
- rascunho » Blog Archive » links for 2008-12-10
- Looking at Code | Have Google host libraries.
- Let Google host your jquery.js file | eKini: Web Developer Blog
- Coderies | taggle.org
- links for 2008-12-12 « boblog
- Daily Digest for 2008-12-12 | andrew . tj . id . au
- BlogBuzz December 27, 2008
- Quick Tip – let someone else serve your CSS framework
- Daily Links | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?
- Weekly Web Nuggets #42 : Code Monkey Labs
- Event Calendar: Submitting Events » Death of a Gremmie
- Shizzle» Blog Archive » Let Google host jQuery for you
- ghettocooler.net » The Links Have Risen
- Wordpress插件：Use Google Libraries - 苍楼笔记
- Carron Media - Extend Google Analytics with jQuery
- Introducting Typekit | Industrial Brand
- Jaap Vossers’ SharePoint Blog » Using Google Ajax Libraries API to load jQuery
- Code a Tricky Login Form With Sliding Signup with jQuery. | CodeTricky
- Mike Panitz's Blog » Using jQuery with CakePHP: The Basics
- Use Google Libraries | 风云阁
- Sunfish Interactive | Blog » 3 reasons why you should let Google host jQuery for you | Encosia
- Varför ska man använda jQuery från Google? | Andreas Karman
- Consuming a Web Service in OBIEE Presentation Services using JQuery CDN | Art of Business Intelligence
- Lightbox Effects, smaller and quicker | Nashville Web Design by GroovySoup
- 5 Fast Ways to Speed Up Your Blog
- Installing JQuery « Lonelycamel's Blog
- ZENVERSE – Fail-Proof Method to load jQuery Library via Google AJAX Libraries API
- Image Caption Slide using jquery | iamkreative - design, kidney and general blog
- Usa el jQuery de Google, anda. | Quenerapú
- Use Google Libraries | Blue Orbs
- 4 Ways Google Wants to Help Your Site’s Speed | Nashville Web Design by GroovySoup
- Splat Labs » Blog Archive » Let Google host it for you!
- Adding jQuery to a custom theme using wp_enqueue_script | Prolific Notion
- Using CDN Hosted jQuery with a Local Fall-back Copy | I love .NET!
- Ubrzajte izradu web stranica pripremom predloška | Kroativ
- What is Content Delivery Network & how to use it with WordPress? | Blog Design Studio
- Random Links #127 | YASDW - yet another software developer weblog
- Featured Slider
- We Love… » Blog Archive » Speed Up Your Web Content Delivery… the essential checklist
- Website Optimisation - iandevlin.com – blog
- 5 Cool Hacks and Tutorials Using WordPress and jQuery | wpConstructs.com - Community Blog for WordPress Lovers
- Lifesize Blog
- Notes from Day One of WordCamp Ireland | Steve Flinter
- uberVU - social comments
- Let Google host the JQuery of your Trac! « Das Weblog zur Person
- How to marry TYPOlight with jQuery | qzminski
- jQuery för nybörjare
- jQuery HTML effects - Trav's Tinkering
- jQuery – de goede manier | Code snipplets
- The Venture Foundation ::
- Teaching Online Journalism » Looking at jQuery for visual journalism
- Rhonda Friberg » Blog Archive » Google AJAX Libraries
- Caching on the Google AJAX Libraries API | Soupgiant
- DrakNet Web Hosting Blog » Site Performance: Tweaking Distribution
- Tips & Tricks « jQuery Refuge
- Simplify you Web Analytics with jQuery - 1918 Internet Services
- Cargar jQuery desde Google | GFDEZ: Laboratorio Web 2010
- RSS mixer service update | BrianDart.net Blog
- 让Google给你的网站加速 | 图腾
- First Time Website Design - Page 11 - Overclock.net - Overclocking.net
- Kestrel Internet Development
- jQuery: » The Official jQuery Podcast – Episode 32 – Dave Ward
- The Official jQuery Podcast
- The Official jQuery Podcast – Episode 32 – Dave Ward
- Dave Ward | Sachin Handiekar
- jQuery CDN을 대안적인 로컬카피와 함께 사용하기 | FRENDS.KR
- this is why you should let Google to host your jQuery | 0t@k-B@L!
- Linee guida per un Web Design più Verde | WebCarpenters
- Self-Baked Social Toolbar with jQuery – Thoughts on Design – trinkaus.cc blog
- Use Google Hosted jQuery in WordPress « T. Longren
- Google CDN Naming Conventions and You | The Hostmaster's Blog :: Web Hosting Tutorials | cPanel Guides | UK Unlimited Domain Web Hosting
- Calling All jQuerys : PubMedia Commons
- jQuery über CDN von Google in Website einbinden | PAS solutions GmbH Blog | Frauenfeld, Thurgau
- CSS OSCommerce » Blog Archive » Cut Page Load time in OSCommerce 2.3 & OSC to CSS
- Site Performance: Tweaking Distribution | A Small Orange
- jQuery deshabilitará el hotlinking
- All jQuery Google Repository Hosting | Devin R. Olsen Web Developer
- Speeding Up Your Blogs/Websites? | Ali Hussain Jiwani
- SOLD and All Change!
- jQuery Filtering - Simple Data Filtering Using jQuery | Think Tank
- Backie » Why not to use Google’s jQuery CDN hosting with WordPress
- 3 reasons why you should let Google host jQuery for you – Encosia | Online Class
- My Bookmarks « Ruman's Blog
- Using Google Ajax Libraries API to load jQuery « Jaap Vossers' SharePoint Blog
- Using jQuery on Google's CDN but having a plan B - Dan Esparza
- How To Let Google Host jQuery For You
- Placeholder Image (s) with jQuery and Bing Image Search API »
- How To Let jQuery.com Host jQuery For You
- How To Let Microsoft Host jQuery For You
- Why Use CDN Hosted jQuery?
- jQuery Tips & Tricks: Create Sliding Horizontal Menu | cramie
- Client-side paging with jQuery | Pros Global TV
- dittocode • A Simple jQuery Modal Box
- .NET - Add jQuery to an ASP.NET Web Application | Oscar's Code
- Referencing External Script Libraries | Dysfunctional Spec
- Tips untuk Meningkatkan Kelajuan Laman Web | Heiswayi Nrird
- Add rel="lightbox" to WordPress Galleries without a plugin
- JQuery linkelés | Kerek egy ég alatt
- Can I Use HTML5 Now? « Almost Humor
- Sandbox SharePoint Online jQuery & jQuery UI WSP package « All things dev
- Los plugins imprescindibles para montar un blog en wordpress. | Gadgetopost
- HyperPac´s site » Blog Archive » Wordpress Visual Editor broken after Update 3.3.1 (again)
- Load jQuery from Google with Fallback to Local File | Mike Newell
- Online jQuery & jQuery UI WSP package of SharePoint 2010/SharePoint 2007 | An Hero
- Web Optimization – Use Google CDN to host jQuery | mesmor
- Coolest web development trick I’ve learned in a long time | Chainsaw on a Tire Swing
- slidebox jquery banner rotator
- Loading jQuery from Google CDN and dependent scripts in WordPress | Yen's Blog
- How to: AJAX Contact Form Using jQuery | Crafted by David
- Hosting your jQuery framework – locally or remotely?
- Web Journal – [littlefixit] » Using Google Hosted Libraries
- Bookmarklet | Elitist
- Query Basics and Methods for Beginners « Tech Snippets
- Building SharePoint Dashboards with Google Chart | sudhirke
- jQuery Basics Part I | Life's for Learning
- jQuery Animate & Highlight Effect » Girl From Out of This World
- Let Google Host jQuery :: Codex :: JDM
- Horizontal & Vertical Scrollbar jQuery Plugin | Complete Web 2.0
- Hvorfor bruge Googles jQuery.js fremfor din egen kopi? | Svend Koustrup
- Coding the Bootstrap Portfolio using Twitter Bootstrap, HTML5 and CSS3 - Webmaster-Deals Blog
- Contact Form 7 spins | Tech4Eleven | Computer Repair and Web Design
- jQuery Basics Part I ← Life's For Learning
- How to Set Up WordPress (No, Really!) / Drew Powers
- How to use AJAX to Query a MYSQL Database and Check availability of a username » Martin Gardner.co.uk
- Add your js and css files to a Prestashop theme | Programmer's Blog
- Google Hosted Libraries – jQuery | Ninja Journal
- Introduction to jQuery | Thomas Wallace
- Progressive Enhancement | Thomas Wallace
- JQuery Foundation’s Dave Methvin helps speed up your website
- Stop WordPress plugins loading jQuery | Adam Dimech's Coding Blog
- Load jQuery From Google CDN in WordPress - Wordpress Code Snippets
- Integrating JQuery AJAX in WordPress using JSON > EJCode in Wilmington DE