Loading jQuery With Two Fallbacks

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