There are a number of large benefits to referencing the jQuery libraries hosted on the Google and Microsoft CDNs. But there are a few drawbacks as well. The primary drawback being: what happens if Google is down. The event is unlikely, but not without precedence.
I have seen a number of posts out there that try to address the issue of CDN failover—where, if Google is down, the Microsoft version is loaded, but there are a few small problems:
- You either have to use document.write (which doesn't work if you use XHTML).
- You have to reference yet another script with a large payload (2-3KB+).
Wouldn't it be nice if there was a way to ensure that jQuery was always loaded? Wouldn't it be great if that method was non-blocking such that the browser could continue to download and parse all content, but at the same time defer all Javascript execution related to jQuery?
These were my goals when I whipped up a small inline script for this very purpose. It's hosted on GitHub and I call it: jQueryReady.
Normally I would simply use document.write would is considered a blocking operation, but when using XHTML document types, document.write isn't supported and silently is ignored. Bad.
Then I tried appending the script tag dynamically to the document head. That doesn't cause any blocking behavior such that any code found after the failed jQuery script tag gets called and you end up with things like "$ is undefined" in your Javascript error console.
One other quick thought that I haven't tried and that is, when the Google CDN fails (as indicated by window.jQuery being undefined), it should be possible to use XMLHttpRequest in a synchronous manner to load jQuery from your own website and then to eval the results which adds jQuery to the window object. I haven't tested this, but it should work. It also depends upon browser support for XMLHttpRequest.
In any case, my objective was to keep jQueryReady miniscule. Why? I didn't want another script I had to reference. Instead I wanted to inline the jQueryReady code onto every single page at the very top. Take a look at the code to see how small it is.
The main way in which jQueryReady works is by wrapping every call to jQuery inside of a function, like so:
jQueryReady(function() {
alert("jQuery is now loaded.");
});
If all of your scripts use jQueryReady, you can be assured that they will not execute until jQuery is loaded.
External Scripts
One remaining quirk in all of this is that external scripts that utilize jQuery may be affected. In other words, the browser will continue to download, parse, and execute external scripts (those referenced with