Best method for selectively loading javascript for mobile web pages?
I'm building a responsive website which re-arranges its layout for mobile sites. That's fine for CSS, but I have a few heavy scripts (slider etc) which appear on the desktop site which I'd rather not serve to mobile clients at all. It's easy enough to hide them in CSS, but then the javascript will still be downloaded and executed and that's obviously not ideal.
What's the best way to prevent such assets from being served at all to mobile devices? I'm thinking some kind of PHP-based detection which will include the relevant javascript in the page only if a non-mobile browser is detected. Either that, or is jQuery's $.browser function sufficient?
I've seen va开发者_如何学运维rious approaches to this but I wondered what the concensus is as to the best method.
Many thanks!
A PHP (or any other server-side language) solution will be the best bet. It might be best to detect when to show it rather than when not to. There are a frightening number of mobile handsets out there and it would be much harder to maintain a list of user agents that are 'mobile' rather than have a list of desktop based user agents.
Of course, this approach comes with it's own caveats.. suppose someone has a modified agent string or you've not included a relatively unpopular browser in there.
Just think about how well you're going to be able to maintain the detection, and think about how fast the markets are moving.
PS. There is a decent helper for generating a basis of agents but it seems quite limited to only smartphones: http://detectmobilebrowsers.mobi/#generator
精彩评论