Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - Can I add a conditional in PHP to only display JS on big screens?

Basically I am running a JavaScript on one of my pages but I don't want it displayed on mobiles. Is this doable in PHP? I've added an enqueue function in my WordPress child theme as per the below:

function load_js_assets() {
if( is_page( 1509 ) ) {
    wp_enqueue_script('custom-script', 'https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js', array('jquery'), '', false);
    wp_enqueue_script('custom-script2', 'https://unidigital.tech/wp-content/themes/picostrap-child/particles.js?ver=5.6', array('jquery'), false, true);
    
} 

}

But I haven't managed to succesfully add a condition to only run the JS on big screens. Can anyone help please?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the following snippet to enqueue javascript only on non-mobile devices.

  

    //Identify is request is coming from a mobile browser.
    function isMobileDevice() { 
        return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo 
    |fone|hiptop|mini|mobi|palm|phone|pie|tablet|up.browser|up.link|webos|wos)/i" 
    , $_SERVER["HTTP_USER_AGENT"]); 
    } 
    
    function load_js_assets() {
        if( is_page( 1509 ) && !isMobileDevice()) {
            wp_enqueue_script('custom-script', 'https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js', array('jquery'), '', false);
            wp_enqueue_script('custom-script2', 'https://unidigital.tech/wp-content/themes/picostrap-child/particles.js?ver=5.6', array('jquery'), false, true);
        }
    }


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...