Enqueuing JS for legacy browsers, the WordPress way

One of the things I love about being a WordPress developer is the ongoing discovery of core functions that make my life easier, or empower me to implement more best practice in my code.

At Make Do one of my chief internal responsibilities as front-end lead is managing our workflow boilerplate Kapow! which we use as a basis for all new WordPress projects.

In the theme component of Kapow! I’ve been happily adding a script to header.php the old fashioned way, which contains various poly-fills and shims to provide enhanced out-of-the-box support for legacy IE versions 7 & 8.

<!--[if lt IE 9]>  ?php%20echo%20esc_url(%20get_stylesheet_directory_uri()%20);%20?/assets/js/header_ie.min.js <![endif]-->

Normally I would rely on WordPress core’s wp_register_script() and/or wp_enqueue_script() functions when introducing JS or CSS assets into a theme to follow best practice, however in this case the need for conditional comments has meant that I’ve had to stick with the old fashioned way. Until this week…

Enter wp_script_add_data() ! This function exists for adding metadata to a script. It accepts three arguments: handle, key and value. You can find the function documentation on the Code Reference. Another gem that I had absolutely no idea about!

The handle is the unique ID you assign to the script when registering and/or enqueuing e.g. legacy_ie.

The key relates to the type of metadata you’re adding and from what I can see conditional is the only documented value available for use. This tells WordPress that the script in question should be enclosed within a conditional comment.

Finally, the value is the content (in this case at least) of the conditional itself e.g. lt IE 9 to detect all versions of IE lower than 9.

This meant I could remove the script from header.php and add the script The WordPress Way as shown in the Gist below.


As you can see we enqueue the script (no need to register unless it’s a dependency that needs to be referenced elsewhere) and then add our script meta to introduce the conditional comments before hooking into wp_enqueue_scripts to invoke the function.

The script will then be added to the header rather than the footer as the wp_enqueue_script() parameter $in_footer defaults to false if not supplied.

And there you have it, a way to introduce scripts wrapped in conditional comments into your theme without polluting your template files.

You truly do learn something new every day!

Published by

Dave Green

Director & Senior Developer at Make Do. WordPress, WooCommerce & Front-end Expert. Mancunian. Husband. Step-dad. Geek. #MaximumEffort

One thought on “Enqueuing JS for legacy browsers, the WordPress way”

Leave a Reply

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