John Davidson

javascript - Do not load JS script on mobile

0 comments
Message:


I try to not load a js script on mobile and I use a cdn and page cache on my wordpress siteweb.


I tryed this to unload the plugin in a php file in mu plugin folder but it didn't work, js is still load on mobile :


function my_non_mobile_plugins() {
return array(

// an array of all the plugins you want to exclude for mobile

'plugin-folder/plugin-file.php',
'another-plugin-folder/another-plugin-file.php',
'no-folder-plugin-file.php'

);
}

function my_is_mobile() {
$is_mobile = false;
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
) {
$is_mobile = true;
}
return $is_mobile;
}

add_filter( 'option_active_plugins', 'my_disable_plugins_for_mobiles' );

function my_disable_plugins_for_mobiles( $plugins ) {

if ( ! my_is_mobile() ) {
return $plugins; // for non-mobile device do nothing
}

$not_allowed = my_non_mobile_plugins(); // get non allowed plugins

return array_values( array_diff( $plugins, $not_allowed ) );

}

I found this to add in function.php in an old post but I don't think it would work :
maybe if I replace ( ! wp_is_mobile() ) by ( wp_is_mobile() ) ?


function custom_load_scripts() { 
// Load if not mobile
if ( ! wp_is_mobile() ) {
// Example script
wp_enqueue_script( 'script-name',get_template_directory_uri() . '/js/example.js', array (), '1.0.0', true );
}
}

add_action( 'wp_enqueue_scripts', 'custom_load_scripts' );

Thnak you so much if you have a solution !



My Answer:
To prevent loading a JS script on mobile devices in WordPress, you can use the `wp_is_mobile()` function to check if the user is accessing the site from a mobile device. Here's an example of how you can modify your code:

php
function custom_load_scripts() {
// Load if not mobile
if ( ! wp_is_mobile() ) {
// Example script
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array (), '1.0.0', true );
}
}

add_action( 'wp_enqueue_scripts', 'custom_load_scripts' );


In this code snippet, the `custom_load_scripts` function will only enqueue the script if the user is not accessing the site from a mobile device. This should prevent the JS script from loading on mobile devices.

Make sure to add this code to your theme's `functions.php` file.

Rate this post

5 of 5 based on 4654 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us