Jquery – Best way to use Google’s hosted jQuery, but fall back to the hosted library on Google fail

cdngoogle-ajax-librariesjquery

What would be a good way to attempt to load the hosted jQuery at Google (or other Google hosted libs), but load my copy of jQuery if the Google attempt fails?

I'm not saying Google is flaky. There are cases where the Google copy is blocked (apparently in Iran, for instance).

Would I set up a timer and check for the jQuery object?

What would be the danger of both copies coming through?

Not really looking for answers like "just use the Google one" or "just use your own." I understand those arguments. I also understand that the user is likely to have the Google version cached. I'm thinking about fallbacks for the cloud in general.


Edit: This part added…

Since Google suggests using google.load to load the ajax libraries, and it performs a callback when done, I'm wondering if that's the key to serializing this problem.

I know it sounds a bit crazy. I'm just trying to figure out if it can be done in a reliable way or not.


Update: jQuery now hosted on Microsoft's CDN.

http://www.asp.net/ajax/cdn/

Best Answer

You can achieve it like this:

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

<script>
       window.jQuery || document.write('<script src="/path/to/your/jquery"><\/script>');
</script>

This should be in your page's <head> and any jQuery ready event handlers should be in the <body> to avoid errors (although it's not fool-proof!).

One more reason to not use Google-hosted jQuery is that in some countries, Google's domain name is banned.

Related Topic