“protocol-less” jQuery with alternate CDN Fall back with local has a fail safe.

Back in September 23, 2010 I posted a link to a fallback from a CDN hosted jQuery with a local host. Now I’m pretty sure most people uses the one Google hosts for them, while the lesser amount of people use Microsoft’s CDN hosted jQuery (I don’t have any stats, so I could be wrong but just call it a hint).

Now if you’re the type to update your jQuery on your site shortly after release, you might notice Google takes a while to have the newest jQuery link, however not Microsoft. Surprised?

What does this mean? If you visit someone who’se using Google’s hosted jQuery, then visit someone else’s site with the same jQuery being referenced it should be cached - thus quicker. But if my assumption about more people using Google’s hosted jQuery over Microsoft’s hosted jQuery is correct then chances are not many other people will have microsoft’s hosted jQuery cached on their machine.

My solution? Call jQuery from Google, check to see if jQuery is undefined, if it is then call jQuery from Microsoft and if for some reason jQuery is still undefined finally fall back to the local host.

For the most part it’s been great, until I noticed for some reason jQuery has the link for Google’s CDN jQuery using HTTPS, and if you’re wondering that might be an issue. Solution? Use a “protocol-less” URL.

So below is my fall back using both “protocol-less” URLs for Google & Microsoft and then falling back to my local copy as my final fail safe.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
        <script>
        //If Google CDN is down, use Microsoft's CDN Network
        if (typeof jQuery == 'undefined') {
            document.write(unescape("%3Cscript src='//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.2.min.js' %3E%3C/script%3E"));}
        //If Microsoft's CDN Network is also down, fall back to local
        if (typeof jQuery == 'undefined') {
            document.write(unescape("%3Cscript src='public/javascripts/jquery-1.5.2.min.js' %3E%3C/script%3E"));}
    </script>

Tags: jquery web