Loading jQuery With Two Fallbacks

CSS-Tricks suggests this code to load jQuery.

However, I’m curious if anybody has done the same thing in functions.php with two fallbacks: the Microsoft hosted jQuery being the first option and locally hosted jQuery being the second, that is, in the case the Google library decides not to load/crashes/gets eaten by a polar bear/etc.

if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
   wp_deregister_script('jquery');
   wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
   wp_enqueue_script('jquery');
}

3 Answers
3

I use a similar pattern to enqueue jQuery from the Google CDN (as the CSS Tricks example). However in my footer (typically footer.php) I’ll usually hard code the following fallback.

<script type="text/javascript">
    if (typeof jQuery === 'undefined') {
        document.write('<script src="https://wordpress.stackexchange.com/questions/78740/<?php echo get_stylesheet_directory_uri(); ?>/js/jquery.min.js" type="text/javascript"><\/script>');
    }
</script>

Let me explain what this does and why I use it…

After jQuery is deregistered, registered, and enequeued, it’ll be injected into the DOM at render time. The script example will need to be included after WordPress renderes wp_header or wp_footer (however you’ve queued it).

The script will check if jQuery is actually an object (if not, it’ll be undefined because of a 404 error or whatever). Then it’ll write out a script tag to load your own copy of jQuery from your theme.

What if the first CDN load fails? Doesn’t that mean WordPress will think jQuery didn’t load? No. WordPress won’t have any knowledge of the CDN failing, but it’ll still think some sort of external resource is being registered and enqueued (as jQuery) and you still gain the benefits of playing nice with other plugins that request jQuery.

I’ve not tried to create a method of attempting a load from Google’s CDN and then Microsoft’s CDN and then my own, however. I’d have to think further on a good way to asynchronously attempt that.

Leave a Comment