How to echo script with conditional logic like styles ?
-
Hello,
I’v been looking for how to echo script with condotonal logic like styles do.
So i made my own solution and i’m posting it here for everyone else who need these
first you shoud add these function:
/** * Adding extra data to scripts **/ if( ! function_exists( 'wp_script_add_data' ) ) : function wp_script_add_data( $handle, $key, $value ) { global $wp_scripts; return $wp_scripts->add_data( $handle, $key, $value ); } endif; // ! function_exists( 'wp_script_add_data' )seccond you need to add filter :
add_filter( 'script_loader_tag', function( $tag, $handle ) { global $wp_scripts; if( isset( $wp_scripts->registered[$handle]->extra['conditional'] ) && $wp_scripts->registered[$handle]->extra['conditional'] ) { $tag = "<!--[if {$wp_scripts->registered[$handle]->extra['conditional']}]>\n" . $tag . "<![endif]-->\n"; } return $tag; }, 10, 2 );and last one, in
wp_enqueue_scriptsaction you should enqueue your script like these:wp_register_script( 'respond', 'https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js', array(), '1.4.2' ); wp_script_add_data( 'respond', 'conditional', 'lt IE 9' ); wp_enqueue_script( 'respond' );and in html youl have:
<!--[if lt IE 9]> <script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js?ver=1.4.2'></script> <![endif]-->That’s it )
Good luck to all
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
The topic ‘How to echo script with conditional logic like styles ?’ is closed to new replies.