Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Conditional JS scripts for WordPress
// !Tool to easily add a "conditional" data to a script.
if ( ! function_exists('sf_conditional_script') ):
function sf_conditional_script( $script, $condition = 'lt IE 9' ) {
return $GLOBALS['wp_scripts']->add_data( $script, 'conditional', $condition );
}
endif;
// !Enqueue script(s).
add_action( 'init', 'sf_init_scripts' );
if ( ! function_exists( 'sf_init_scripts' ) ) :
function sf_init_scripts() {
wp_enqueue_script( 'selectivizr', get_template_directory_uri() . 'polyfills/selectivizr.min.js', array( 'jquery-core' ), '1.0.2', true );
sf_conditional_script( 'selectivizr' );
}
endif;
// !Add the conditional comments.
add_filter( 'script_loader_tag', 'sf_conditional_scripts', PHP_INT_MAX, 3 );
if ( ! function_exists( 'sf_conditional_scripts' ) ) :
function sf_conditional_scripts( $tag, $handle, $src ) {
global $wp_scripts;
if ( $tag && ! $wp_scripts->do_concat && $conditional = $wp_scripts->get_data( $handle, 'conditional' ) ) {
return "<!--[if $conditional]><script type='text/javascript' src='$src'></script><![endif]-->\n";
}
return $tag;
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment