How do I remove scripts for responsive mobile

2019-08-27 03:43发布

问题:

I have a plugin.js that combine all my plugins for my responsive build. This plugin.js is unnecessarily bulky for mobile. I would like to create 2 plugin.js to switch between for mobile or desktop.

What is the best practice for reducing overhead for mobile scripting?

Examples: I have a complicated jQuery slider for desktop viewing but I would like that script not to load for mobile.

For this project i'll be using: HTML5, Wordpress, jQuery, Modernizr.

回答1:

It depends what you define as mobile. If it's all devices below a certain width, you can test for that, and then prevent the script running with an if statement.

$(function(){
    var mobile;
    if (window.width < 481) {
        mobile = 1; 
    }

    if (!mobile) {
    // All your stuff.
    }
});


回答2:

I would not recommend using JavaScript to check the device. What are you using for the server side? I have used the free PHP mobile detect class with much success. It can detect mobile tablet or specific manufacturer as well eg. iPad. It is super easy to use also. Then you could generate the page based on that or redirect to a specially formatted mobile site. using javascript is very unreliable and some people could have it turned off in their browser, not likely but it happens. If you do it on the server you dont have to worry about things like that.