In a WordPress theme, how do you conditionally include scripts for ie8 and below? This is primarily to apply polyfills for various html5/css3 features. I see that wp has the $is
For WordPress 4.2+
Use wp_script_add_data to wrap the script in a conditional comment:
wp_enqueue_script( 'html5shiv', '//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv.js' );
wp_script_add_data( 'html5shiv', 'conditional', 'lt IE 9' );
wp_enqueue_script( 'respond', get_template_directory_uri() . '/js/respond.min.js' );
wp_script_add_data( 'respond', 'conditional', 'lt IE 9' );
Just make sure you register the script before invoking wp_script_add_data
(registering is handled by wp_enqueue_script
above), and that the first argument you pass to wp_script_add_data
matches the first argument you passed when you registered the script.
For WordPress 4.1
You can use the script_loader_tag filter today to enqueue scripts wrapped in conditional comments. Here’s an example implementation:
wp_enqueue_script( 'html5shiv', '//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv.js', array(), '3.7.2', false );
add_filter( 'script_loader_tag', function( $tag, $handle ) {
if ( $handle === 'html5shiv' ) {
$tag = "";
}
return $tag;
}, 10, 2 );
And if you want to include more than one script in the same way, you can use something like:
// Conditional polyfills
$conditional_scripts = array(
'html5shiv' => '//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv.js',
'html5shiv-printshiv' => '//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv-printshiv.js',
'respond' => '//cdn.jsdelivr.net/respond/1.4.2/respond.min.js'
);
foreach ( $conditional_scripts as $handle => $src ) {
wp_enqueue_script( $handle, $src, array(), '', false );
}
add_filter( 'script_loader_tag', function( $tag, $handle ) use ( $conditional_scripts ) {
if ( array_key_exists( $handle, $conditional_scripts ) ) {
$tag = "";
}
return $tag;
}, 10, 2 );