手機端和PC端分別加載不一樣的js文件

分手機端和PC端其實方法不少,咱們在響應式設計、響應式網站建設中常常碰到此類需求。下面說說咱們在項目中遇到的需求:javascript

手機端和PC端分別加載不一樣的js客服代碼(注意:是要在PC和手機端分別加載不一樣的js文件)java

第一種方法(簡單型):android

<script type="text/javascript">  
// 根據屏幕尺寸  
if (screen && screen.width > 480) {  
document.write('<script type="text/javascript" charset="utf-8" src="123.js"><\/script>');  
}  
  
// userAgent判斷  
if( /Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)){  
document.write('<script type="text/javascript" charset="utf-8" src="123.js"><\/script>');  
}  
</script> 

 

 第二種方法(已測試經過,項目真實在用):web

  
<script type="text/javascript">  
function browserRedirect() {  
var sUserAgent = navigator.userAgent.toLowerCase();  
var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";  
var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";  
var bIsMidp = sUserAgent.match(/midp/i) == "midp";  
var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";  
var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";  
var bIsAndroid = sUserAgent.match(/android/i) == "android";  
var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";  
var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";  
// document.writeln("您的瀏覽設備爲:");  
if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {  
  
// alert("手機瀏覽!");  
  
document.write('<script type="text/javascript" charset="utf-8" src="123.js"><\/script>');  
} else {  
  
// alert("PC瀏覽!");  
document.write('<script type="text/javascript" charset="utf-8" src="123.js"><\/script>');  
}  
}  
browserRedirect();  
</script>  

 

這樣子咱們直接在PC端和手機端分別輸出不一樣的js。因此,咱們在手機端和PC端分別加載不一樣的js的需求完美解決了。 windows

相關文章
相關標籤/搜索