How to Load Scripts only on Mobile Devices

If you have used PerfMatters, you probably know that it is possible to load scripts on certain pages and on different type of devices.

I was wondering how that could be done by adding custom code to the functions.php file

Fortunately it is possible and the solution is not that hard to implement.

Code to Load Scripts Only on Mobile Devices

I found this code on StackOverFlow that does exactly what we are trying to do

add_action( 'wp_enqueue_scripts', 'jung_mobile_only_js');
function jung_mobile_only_js(){
    if( wp_is_mobile() ){
        wp_enqueue_script( 'jung-mobile-only-js', 'URL_TO_YOUR_JS_FILE_HERE', array(), '1.0', true );
    }
}

I am using the code to load the menu.min.js from generatepress only on mobile devices and I haven’t encountered any problems.

Take this into Consideration

You have to dequeue the file that you want to load conditionally.

You can use this code snippet to do that.

add_action( 'wp_enqueue_scripts', 'remove_menu_scripts', 50 );
function remove_menu_scripts() {
	wp_dequeue_script( 'Script-You-Want-to-Remove' );
}

Then we you can use the code snippet taken from StackOverFlow

You just need to add the URL of the script that should be load only on mobile devices

add_action( 'wp_enqueue_scripts', 'jung_mobile_only_js');
function jung_mobile_only_js(){
    if( wp_is_mobile() ){
        wp_enqueue_script( 'jung-mobile-only-js', 'URL_TO_YOUR_JS_FILE_HERE', array(), '1.0', true );
    }
}

Then add the code to your functions.php file or use a code snippets plugin.

I use a code snippets plugins because I don’t want future updates to override my code snippets

JM

Sobre Jose manuel

I am José Manuel. I started a WordPress blog in 2011 as a hobby to use it a part of my teaching and I fell in love with blogging & WordPress.

I am writing about things I know and things that I am learning. I hope you find some of the things I write useful.