Conditional Loading Of Script In WordPress

While you create your WordPress theme or plugins, in such case, you might need to enqueue the custom script to be loaded only in the Internet Explorer browser. So, it might come in your head that, is it really possible? The answer to this is, yes, it is possible. WordPress has already provided such feature developed inside it. The code to be enqueued for this conditional loading of script in WordPress is provided below as:

function theme_slug_scripts() {
wp_enqueue_script('html5shiv', get_template_directory_uri() . '/js/html5shiv/html5shiv' . $suffix . '.js', false);
wp_script_add_data('html5shiv', 'conditional', 'lt IE 9');
add_action('wp_enqueue_scripts', 'theme_slug_scripts');

What the above code does is, it enqueues the html5shiv custom JavaScript in the header of the document and then below the function, which is wp_script_add_data(), adds the conditional statement to be loaded for the enqueued html5shiv script, ie, it wraps that script to be loaded only on the Internet Explorer browser versions less than 9, inside the if condition.

The image below is shown as how it is rendered in the front-end, when used with view source feature of the browser, when it is being applied properly in your project:


Now, if you have followed this tutorial properly and is success in loading the required scripts conditionally for your WordPress project, then, we can assume that you are now more familiar on conditional loading of script in WordPress. But, if you are still confused on it and want to know more about it, then, just comment below in the comment box and we will follow it up.

Post navigation

Bishal Napit

Bishal Napit is a WordPress theme developer from Tansen, Palpa, with a passion to learn more on WordPress.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.