Don’t load scripts if on mobile/tablet

The question:

Would like to ask the question is it possible to stop the laoding of some scripts when viewed on a mobile/tablet device ?

In the theme functions file you have wp_enqueue_script(...). How would you go about loading if based on device/screen size..

Is this possible?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

wp_is_mobile() does not really solve your problem completely. To be honest here, there is no logic in WordPress to achieve what you want

  • First of all, wp_is_mobile() only checks for mobile devices. Tablets are excluded from this

  • Window sizes are determined on browser side, not server side, so there are no way for php to check window size. That is why there are also no function in WordPress that can detect a window size

The only probable way to do this is to make use of javascript. I’ve seen examples where javascript is used to determine window size and then do load something accordingly. I haven’t tested anything like this yet, and frankly, that would also be off topic here. I would suggest that you try a few google searches and testing out a few solutions as I suggested

Method 2

Try wp_is_mobile function to check, like:

function theme_name_scripts() {
    if( ! wp_is_mobile() ) {
        wp_enqueue_style( 'style-name', get_stylesheet_uri() );
        wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
    }
}

add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

Method 3

Try this:

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' );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment