Last active
July 28, 2021 10:28
-
-
Save Screenfeed/0bfe9441b4aa6c7b19b7 to your computer and use it in GitHub Desktop.
Conditional JS scripts for WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// !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