仅为移动设备加载JQuery Mobile脚本

gio*_*ine 12 javascript mobile jquery-mobile

我有一个必须在移动设备上正确显示的网页.为此,我在页面的头部加载了JQuery Mobile脚本.head标签看起来像这样:

<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>
Run Code Online (Sandbox Code Playgroud)

并在页面的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;
}
Run Code Online (Sandbox Code Playgroud)

Nac*_*ket 14

很难检测到您的设备是移动设备还是平板电脑还是带触摸的大屏幕,但首先要注意

  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']
});
Run Code Online (Sandbox Code Playgroud)

编辑:

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