Enqueue Conditional Scripts & Styles for Internet Explorer

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:

add_action( 'wp_enqueue_scripts', 'cs_conditional_scripts_and_styles' );
/**
* Enqueue styles and scripts conditionally.
*
* @link https://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
* @since 1.0.0
*/
function cs_conditional_scripts_and_styles() {
/**
* Enqueue flexiility.js script for users of IE9 and below.
* @link: https://github.com/10up/flexibility
*/
wp_enqueue_script( 'flexibility', get_stylesheet_directory_uri() . '/assets/js/flexibility.js', [], '20160502', true );
wp_script_add_data( 'flexibility', 'conditional', 'lte IE 9' );
}
view raw functions.php hosted with ❤ by GitHub

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().

Reader Interactions

Leave a Reply

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