In an HTML template I found the following two lines of code that's loading external scripts. The first one is very familiar jQuery library from the CDN, but the second one is odd to me.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.9.1.min.js"><\/script>')</script>
As a WordPress developer, I can enqueue the first one with wp_enqueue_script()
:
function scripts() {
wp_enqueue_script( 'jquery-latest', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' );
}
add_action('wp_enqueue_scripts', 'scripts');
But I'm wondering, how to do the second one?
So my question is twofold:
- What's that line of code? Is that a fallback only triggered when the CDN fails?
- How to enqueue but hard code the second line in WordPress?
EDIT
After the answer of @RobSchmuecker I actually got the point. But with lack of experience in that way seeking the right way of execution actually, here is my code:
function scripts() {
wp_enqueue_script( 'jquery-latest', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js' );
wp_localize_script( 'jquery-fallback', 'styleSheetURL', get_stylesheet_directory_uri() );
wp_enqueue_script( 'jquery-fallback', get_template_directory_uri() . '/js/jquery-fallback.js', array( 'jquery-latest' ) );
}
add_action('wp_enqueue_scripts', 'scripts');
And I set the jquery-fallback.js
in your way, only with the following line:
window.jQuery || document.write('<script src="' + styleSheetURL + '/js/jquery-1.11.1.min.js"><\/script>');
File hierarchy is:
/ functions.php
/ js
/ jquery-1.11.1.min.js
/ jquery-fallback.js
But I'm failing to load the jQuery from the local server.
EDIT 2
The HTML output seems correct. I speculated the jquery-fallback.js
file from the browser, and it's showing the exact file as mentioned earlier. But I changed the path to styleSheetURL + '/jquery-1.11.1.min.js
.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js?ver=3.9.1"></script>
<script type="text/javascript" src="http://localhost/PROJECTDIRECTORY/wp-content/themes/MYTHEME/js/jquery-fallback.js?ver=3.9.1"></script>
But still the console is saying there are at least 4 dependent jQuery calls are missed.