Detect client browser support JavaScript in the WordPress theme

JavaScript is an essential part of the modern web, allowing developers to create interactive and dynamic websites. It is also used to power many of the features of WordPress, from the user interface to plugins and themes. However, not all browsers support JavaScript, so it’s important to detect which browsers your visitors are using in order to provide the best user experience.

In WordPress, there are several ways to detect if the client browser supports JavaScript. The first is to use the “wp_enqueue_script” function, which allows you to specify which browsers should receive a particular script.

Another way to detect client browser support for JavaScript is to use the “wp_script_is” function. This function allows you to check if a particular script has already been enqueued.

Finally, you can use the “wp_browser_detect” function to detect which browser the visitor is using. This function returns an array containing information about the browser, including the name, version, and whether or not it supports JavaScript.

Another way to detect if the user browser supports JavaScript in WordPress or not, is using pure JS like the following code.

Open “functions.php” and add below code.

function hs_body_classes( $classes ) {

    // Helps detect if JS is enabled or not.
    $classes[] = 'no-js';

    return $classes;
}
add_filter( 'body_class', 'hs_body_classes' );

function hs_supports_js() {
    echo '<script>document.body.classList.remove("no-js");</script>';
}
add_action( 'wp_footer', 'hs_supports_js' );

In the first function, we add the “no-js” class to the body class. In the second function, if the browser supports JavaScript, the code will run and delete the “no-js” class.

If the body has a “no-js” class, then the browser doesn’t support JavaScript or it is disabled.

By using these functions, you can easily detect which browsers support JavaScript and provide the best user experience for your visitors. It’s important to remember, however, that not all browsers support JavaScript, so you should always provide a fallback solution for those browsers.