2012-07-05 51 views
11

我有一个必须在移动设备上正确显示的网页。 为此,我在页面头部加载了JQuery Mobile脚本。头标签如下所示:仅针对移动设备加载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; 
} 

回答

14

它很难检测到您的设备是手机或平板电脑或触摸, 巨大的屏幕,但下手

  1. 使用脚本利用http://detectmobilebrowsers.com/
  2. 测试,以检测http://yepnopejs.com/

这样的(应该jQuery脚本工作从http://detectmobilebrowsers.com/):

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

编辑:

https://github.com/borismus/device.js也可以看看,基于条件加载内容。我不确定它是否会允许你加载条件JS文件。

+0

谢谢,虽然我发现检测移动浏览器的功能似乎工作,detectmobilebrowsers肯定是好得多:) 我的主要问题是如何加载基于该条件的JQuery脚本:( – giocarmine 2012-07-05 12:25:57

+0

使用正常的Javascript链接detectmobilebrowser.com – Nachiket 2012-07-05 14:44:18

+0

它似乎也许我真的不需要做一个有条件的JS脚本加载,所以我认为你提供的所有链接都超过我需要:) 再次感谢你! – giocarmine 2012-07-05 15:34:33

2

如何确定是否使用基于设备宽度的移动布局,比如像Twitter Bootstrap这样的CSS框架呢?这样,你可以设计使用jQuery移动的小设备和其他与香草jQuery的其他设备?我认为,使用yepNope或类似软件进行测试仍然适用。

相关问题