I have a site which uses Google's API's for jquery and a fallback for jquery. The problem is that I can't get the fallback to happen immediately after the jquery api attempt. What happens is that the fallback file is added after a range of plugin scripts which require jquery and then fails. How can I change the order or location where these plugin scripts are added? Below just gives me the registered files:

var_dump( $GLOBALS['wp_scripts']->registered ); 
  • Why don't you add your fallback code into a plugin and save your plugin in the MU folder codex.wordpress.org/Must_Use_Plugins. Then this will run before any other plugins.
    – TomC
    Jul 4 '16 at 13:56
  • It did the trick. Would mark it as the answer for this problem.
    – Alex C
    Jul 4 '16 at 15:02

Add your fallback code into a plugin and save your plugin in the MU folder: http://codex.wordpress.org/Must_Use_Plugins.

Then this will run before any other plugins


Here's a slightly different way of doing it, replacing the existing enqueued script with the CDN and adding a fallback. Also matches to your existing jQuery version in WordPress. Found it pretty reliable in practice:

function jquery_cdn_with_fallback() {
    global $wp_version;
    // get the jquery handle depending on WP version
    $jqueryhandle = (version_compare($wp_version, '3.6-alpha1', '>=') ) ? 'jquery-core' : 'jquery';
    // get the version of built-in Jquery in WordPress
    $wpjquery = $GLOBALS['wp_scripts']->registered[$jquery_handle]->ver;

    $jquery = 'https://ajax.googleapis.com/ajax/libs/jquery/'.$wpjquery.'/jquery.min.js';

    // replace the existing jquery script URL
    wp_register_script($jqueryhandle, $jquery, false, $jqueryversion, true);

    // add fallback via script_loader_tag filter
    add_filter('script_loader_tag','jquery_fallback', 10, 2);
    function jquery_fallback($scripttag, $handle) {
        global $wp_version;
        $jqueryhandle = (version_compare($wp_version, '3.6-alpha1', '>=') ) ? 'jquery-core' : 'jquery';
        if ( ($handle == $jqueryhandle) && (strstr($scripttag,'jquery.min.js')) ) {
            $jquery = urlencode(site_url().'/wp-includes/js/jquery/jquery.js');

            // instant fallback to local WP jquery on failure
            $fallback = "</script><script>if (!window.jQuery) {document.write(unescape('%3Cscript src=\"".$jquery."\"%3E%3C\/script%3E'));}</script>";
            $scripttag = str_replace('</script>',$fallback, $scripttag);
        return $scripttag;

Adapted it for WP based on this answer: https://stackoverflow.com/questions/1014203/best-way-to-use-googles-hosted-jquery-but-fall-back-to-my-hosted-library-on-go

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.