为移动网页选择性加载 javascript 的最佳方法?
我正在构建一个响应式网站,该网站会为移动网站重新安排其布局。这对于 CSS 来说很好,但是我有一些繁重的脚本(滑块等)出现在桌面网站上,我根本不想为移动客户端提供服务。将它们隐藏在 CSS 中很容易,但是 JavaScript 仍然会被下载并执行,这显然不理想。
阻止此类资产向移动设备提供服务的最佳方法是什么?我正在考虑某种基于 PHP 的检测,仅当检测到非移动浏览器时,才会在页面中包含相关的 javascript。或者说 jQuery 的 $.browser 函数就足够了?
我见过各种方法,但我想知道最佳方法的共识是什么。
非常感谢!
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 various approaches to this but I wondered what the concensus is as to the best method.
Many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PHP(或任何其他服务器端语言)解决方案将是最好的选择。最好检测何时显示它,而不是何时不显示。移动手机的数量多得惊人,维护“移动”用户代理列表比维护基于桌面的用户代理列表要困难得多。
当然,这种方法有其自身的警告。假设有人修改了代理字符串,或者您没有在其中包含相对不受欢迎的浏览器。
只需考虑一下您将能够在多大程度上维持检测,并考虑一下市场变化的速度。
附言。有一个不错的助手可以生成代理的基础,但它似乎仅限于智能手机: http://detectmobilebrowsers.mobi/ #生成器
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