【问题标题】:Load JQuery Mobile script only for mobile devices仅为移动设备加载 JQuery Mobile 脚本
【发布时间】:2012-07-05 09:58:48
【问题描述】:

我有一个必须在移动设备上正确显示的网页。 为此,我在页面头部加载了 JQuery Mobile 脚本。头部标签如下所示:

<head> 
    <title>Page Title</title> 

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
</head>

并且在页面的body元素中使用了data-role属性来显示东西。 这些页面在移动设备上看起来相当不错,但即使请求来自非移动浏览器,它看起来也很相似。

我想知道是否有人知道仅当请求来自移动设备时才加载 JQuery Mobile 脚本的方法。

到目前为止,我尝试使用一个功能来检测我的用户代理并加载脚本(如果它是移动设备):

function init() {

    if(isMobile()) {
        document.write('<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />');
document.write('<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>');
dcument.write('<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>');
    }
}


function isMobile() {

    if(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPad|iPod/i) || navigator.userAgent.match(/IEMobile/i))
            return true;
        return false;
}

【问题讨论】:

    标签: javascript mobile jquery-mobile


    【解决方案1】:

    很难检测您的设备是移动设备、平板电脑还是触摸式大屏幕, 但要从

    开始
    1. 使用脚本检测来自http://detectmobilebrowsers.com/
    2. 使用http://yepnopejs.com/ 进行测试

    像这样(应该适用于来自 http://detectmobilebrowsers.com/ 的 jQuery 脚本):

    yepnope({
      test : jQuery.browser.mobile,
      yep  : 'mobile_specific.js',
      nope : ['normal.js','blah.js']
    });
    

    编辑:

    还可以查看https://github.com/borismus/device.js,以根据条件加载内容。我不确定它是否允许您加载条件 JS 文件。

    【讨论】:

    • 谢谢,虽然我发现检测移动浏览器的功能似乎有效,但detectmobilebrowsers 肯定要好得多 :) 我的主要问题是如何根据该条件加载 JQuery 脚本 :(
    • 使用detectmobilebrowser.com中提供的普通Javascript链接
    • 看来我可能真的不需要对js脚本进行条件加载,所以我认为你提供的所有链接都超出了我的需要:)再次感谢你!跨度>
    【解决方案2】:

    如何确定是否使用基于设备宽度的移动布局,例如 Twitter Bootstrap 等 CSS 框架?这样,您可以使用 jQuery mobile 为小型设备设计,而使用 vanilla jQuery 为其他设备设计?我认为使用 yepNope 或类似的测试仍然适用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      相关资源
      最近更新 更多