Craig Simpson

Web developer from Moray, Scotland

Enqueue Conditional Scripts & Styles for Internet Explorer

2nd May 2016

No Comments

It can be challenging to develop websites that look good across all of the different web browsers. Different browsers have their own quirks and nuances, which you’ll only really become aware of with experience.

Recently I’ve started using Flexbox on a couple of projects, and really like that it makes complex layout and positioning issues all but disappear. But as you can see, support for Flexbox on Internet Explorer 8 and 9 is non-existant. When working for agencies, I’m often building WordPress themes and websites for large companies many of whom are stuck on dated IT equipment that won’t support the latest bells and whistles.

But never fear, the talented folks over at 10up have come to the rescue, with their excellent flexibility script. It’s a JavaScript polyfill designed to allow support for Flexbox on older versions of Internet Explorer.

In order to make use of this script within WordPress, we can use wp_enqueue_script(), and it will be loaded on every page. However, that means the script will be loaded for everyone and not just users of Internet Explorer. What we really need is to make sure that the script only loads for users of Internet Explorer version 9 or lower. WordPress has a built in function for that, too.

To achieve the conditional loading of our script, we would use the following snippet:

1add_action( 'wp_enqueue_scripts', 'cs_conditional_scripts_and_styles' );
2/**
3 * Enqueue styles and scripts conditionally.
4 *
5 * @link https://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
6 * @since 1.0.0
7 */
8function cs_conditional_scripts_and_styles() {
9 
10 /**
11 * Enqueue flexiility.js script for users of IE9 and below.
12 * @link: https://github.com/10up/flexibility
13 */
14 wp_enqueue_script( 'flexibility', get_stylesheet_directory_uri() . '/assets/js/flexibility.js', [], '20160502', true );
15 wp_script_add_data( 'flexibility', 'conditional', 'lte IE 9' );
16 
17}

And if you check your page in your browser inspector, you’ll see that the script has been wrapped in conditional tags, and will now only be loaded by visitors using Internet Explorer 9 or below.

You can modify the conditional statement to target other versions, and with other conditions – the lte part of our wp_script_add_data() can be changed to:

  • lt Less than.
  • lte Less than or equal to.
  • gt Greater than.
  • gte Greater than or equal to.

The wp_script_add_data() function also has a counterpart for loading conditional stylesheets, the same principle applies, but you would instead use wp_style_add_data().

Leave a Reply

Your email address will not be published. Required fields are marked *