Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a script only for mobile on wordpress

I'm trying to make load a simple javascript code on wordpress just on mobile in header.

I've tried plugins and to code but It seems not within my reach and need help :D

Ciao!

like image 326
Jung dev Avatar asked Dec 24 '22 09:12

Jung dev


2 Answers

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' );
like image 173
sandeep kumar shaw Avatar answered Jan 21 '23 17:01

sandeep kumar shaw


Other answers have suggested using the WordPress function wp_is_mobile() when enqueuing a script. Be very careful doing this. If you use caching plugins or if your host caches PHP requests, this could make this method useless.

Instead, I would recommend loading the JavaScript file and testing to see if the browser is mobile or not based on the screen size of the device using JavaScript.

Here is an example (uses jQuery):

$( document ).ready(function() {      
    var isMobile = window.matchMedia("only screen and (max-width: 760px)");

    if (isMobile.matches) {
        //Add your script that should run on mobile here
    }
 });
like image 42
Marc Avatar answered Jan 21 '23 18:01

Marc