Register and enqueue conditional (browser-specific) javascript files?

WP_Scripts and WP_Styles classes are behind wp_enqueue_script and wp_enqueue_style functions. If you take a look at classes implementation (scripts and styles) then you will see that WP_Scripts class doesn’t support any kind of conditional scripts, but! you can see that WP_Styles does! The problem is that wp_enqueue_style doesn’t allow you to setup condition.

So we have to make a small hack:

add_filter( 'wp_enqueue_scripts', 'wpse2345_enqueue_scripts' );
function wpse2345_enqueue_scripts() {
    wp_enqueue_style( 'mystyle', 'url/of/my/style.css', array(), '1.0.0' );

    global $wp_styles;
    $wp_styles->registered['mystyle']->add_data( 'conditional', 'lt IE 9' );
}

Such hack become possible, because all registered styles are stored in registered field of WP_Styles class. Each of registered style is an object of _WP_Dependency class, which allow you to add extra data.

Unfortunately this hack is not working for scripts.

Additional Information:
I was actually going through the code in Aaron Campbell’s Essence Theme last night and noticed that he was calling both a browser conditional script and style.

/**
 * @var WP_Scripts
 */
global $wp_scripts;
// Conditionally load this only for IE < 9
$wp_scripts->add_data( 'html5', 'conditional', 'lt IE 9' );

/**
 * @var WP_Styles
 */
global $wp_styles;
// Conditionally load this only for IE < 8
$wp_styles->add_data( 'blueprint-ie', 'conditional', 'lt IE 8' );

There is also a ticket and patch but it’s not in core yet. Obviously the conditional script won’t work without the patch but one thing to note is that you can use the add_data method directly inside your function that is attached to the wp_enqueue_scripts action.

Leave a Comment