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!
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' );
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With