How do you load js and style resources from CDN with local fallback using wp_enqueue_scripts?

Since 4.5 there is a function that lets you append inline js to an enqueued js file, it is called wp_add_inline_script.

Now, this function does not let you add any js code that has a </script> in it for security reasons. But when you look at the wp_add_inline_script source code, you can see that it is just a wrapper for a wp_scripts()->add_inline_script() call with some added string parsing for malicious strings.

So, if you don’t mind using this function directly without the added security layer of wp_add_inline_script which parses for security problems (just the </script> check for now, but might be more in the future) then you can do the following:

function _enqueue_my_scripts() {
  // the normal enqueue
  wp_enqueue_script( 'jquery-cdn', 'https://code.jquery.com/jquery-3.3.1.min.js' );
  // our custom code which will check for the existance of jQuery (in this case)
  wp_scripts()->add_inline_script( 'jquery-cdn',
    "window.jQuery || document.write('<script src=\"".get_template_directory_uri() ."/js/jQuery.js\">\\x3C/script>')", 'after');
}
add_action('wp_enqueue_scripts', '_enqueue_my_scripts', 100);

Make sure to copy the wp_scripts() call exactly and only switch out the library test (‘window.jQuery’) for a test of the library you want to test and the ‘/js/jQuery.js’ part for a path to your library, because the string gets parsed before output and only this way it gets printed in the correct way.

That code above will give you

<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
window.Swiper || document.write('<script src="http://localhost/wordpress/wp-content/themes/wp-theme/js/jQuery.js">\x3C/script>')
</script>

in your HTML.