Site icon WP Smith

Conditionally Enqueue Script/Styles By Browser

Currently WordPress's wp_enqueue_script() or wp_enqueue_style() does not accept extra data to add HTML conditional markup (see Ticket #16024). For example, using wp_enqueue_script(), you cannot output something like this:

Instead, you will need to take the approach of most and add this to wp_head manually. And usually the "best" solution is something like this:

Although, this will result in the code being outputted regardless of the version of IE the visitor may be using.

There is, however, one little known function, used in the admin dashboard, that can be utilized to conditionally enqueue scripts and/or styles: wp_check_browser_version().

This function, found in wp-admin/includes/dashboard.php, checks to see if a site transient is available (cached for 1 week). If it is not available, then wp_check_browser_version() hits the WordPress Browse Happy API. Currently, there is no way to change a site transient expiration time (Ticket #21330), which would be advantageous here (though WordPress uses MD5 to transcode the $_SERVER['HTTP_USER_AGENT'] converting Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11 to 93ce43dc55bd29ecc99e83ca12b5d7f4, which is friendlier for the options table).

When you access the Browse Happy API ($response = wp_check_browser_version();), here is the basic response array:

Array (
    [platform] => Windows
    [name] => Internet Explorer
    [version] => 8.0
    [update_url] => http://www.microsoft.com/windows/internet-explorer/
    [img_src] => http://s.wordpress.org/images/browsers/ie.png
    [img_src_ssl] => https://wordpress.org/images/browsers/ie.png
    [current_version] => 9
    [upgrade] => 1
    [insecure] =>
)

The names of the major browsers are as follows (of the ones I tested):

The versions returned are always those found in the About Browser (e.g. About Google Chrome: 20.0.1132.57).

While the WordPress dashboard focuses primarily on insecure and upgrade as the key to display Browser Nag Meta Box, we can use the function to get the name of the browser and the version.

So for example, if we want to enqueue a script for browsers less than IE 9, we can do something like this:

So while I could have used wp_check_browser_version() to get the browser, it makes an external API call, which I prefer to avoid if possible. Instead WordPress has some built-in simple browser detection:

Here I ensure that we have IE first via $is_IE, then I make the API call for further conditional testing.

Now, we don't need HTML conditional statements to conditionally link scripts or styles, and we can follow WordPress best practices to use wp_enqueue_script() and wp_enqueue_style(). While this is not the best approach per se, it is until the ticket (#16024) for this is resolved.