Over time, Internet Explorer (IE) is getting better at rendering web pages how we want them, but while IE7 and earlier versions still have a (fast-fading) grip, we sometimes still need to provide exclusive styles to make them render our sites in an acceptable way. That is where conditional style sheets are used.
Update: https://garyjones.io/enqueued-style-sheet-extras#ie
The first function enqueues a reference to a style sheet file called style-ie7.css
in our child theme folder. Using the wp_enqueue_style()
is the correct way of adding style sheet references, as amongst other reasons, it provides a handle that we end up using in the second function. We hook the function in with a priority of 200
. This make sure it appears after any other style sheets that you or a plugin have added in.
The second function surrounds what will be the <link>
markup with a conditional comment to target only browsers that are less than or equal to (the lte
bit) IE7. Other conditional comments are available, but this is by far the most common approach, with IE6- and IE7-specific styles thrown into the same file, to avoid an extra HTTP request. Browsers which aren’t IE just see the output as one big comment and promptly ignore it.
Credit to Michael Fields for highlighting script_loader_tag
Is there a way to do this with scripts? I don’t think script_loader_tag exists even with WordPress 3.4.1. style_loader_tag works perfectly, though.
What is it you want to do with scripts? Just load them for IE?
If so, you’d be better referencing the script for everyone, but check in the script itself for feature detection (rather than browser-sniffing).
The script is the html5shiv. I’d rather wrap the link with IE conditional statements than have every browser load it. At the moment, I’ve just hard coded it instead of enqueing the script as a workaround.
An alternate method for the conditional styles is to use $wp_styles:
function enqueue_styles() {
global $wp_styles;
wp_register_style( $handle, $src, $deps, $ver, $media );
wp_enqueue_style($handle);
$wp_styles->add_data($handle, 'conditional', 'lt IE 9' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_styles' );
It doesn’t work on scripts though, or not as far as I know (and script_loader_tag still hasn’t been added to WP as of WP 3.5).
See the link at the top of this article – it already offers code similar to what you’ve suggested :-)
For negative conditionals it is similar. This is the method to use as the wp_enqueue_style does not format correctly (as per http://core.trac.wordpress.org/ticket/16118)
// Global Styles needs different method for adding negative conditional comments
add_filter( ‘style_loader_tag’, ‘neg_style_sheet_conditional’, 10, 2 );
function neg_style_sheet_conditional( $tag, $handle ) {
if ( ‘bbb-global-style’ == $handle )
$tag = ‘‘ . “n” . $tag . ‘<!–‘ . “n”;
return $tag;
}