2012-07-05 77 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或類似軟件進行測試仍然適用。

相關問題