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');
}
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.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.
To expand on what Jared Cobb wrote into a hook and a more simple check.
There are real problems with this, if any plugins hook into
wp_enqueue_script
they might still break, especially is they are using$deps
.ps. I removed the Php for the
src
since you can use your theme dir or the wp-includes functionincludes_url
, for example.Honestly the small footprint loading Jquery locally provides is often a better solution to using a CDN, that way you don’t have to worry about fallback or outdated CDN’s.
As far as I can tell there is no fall back within their functions.php, what that functions.php is doing is telling JQUERY not to be loaded locally and load it via the CDN ensuring that no plugins can HOOK it in for a 2nd time.
If your looking for similar code but with a fall back here you go: