Today I come across a code snippet which uses JavaScript to check different mobile devices and then loads different CSS files accordingly. As we know that there are mobile devices with different screen sizes, it's always troublesome for web developers to develop cross browser and cross device compatible codes. Hope this one can help those who develop web apps on mobile devices.
// Check whether it's a mobile device // wukong.name 20130716 if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))){ if(window.location.href.indexOf("?mobile")<0){ try{ if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)){ // Check whether the environment is Android|webOS|iPhone|iPod|BlackBerry setActiveStyleSheet("style_mobile_a.css"); }else if(/iPad/i.test(navigator.userAgent)){ // Check whether the environment is iPad setActiveStyleSheet("style_mobile_iPad.css"); }else{ // If other mobile devices setActiveStyleSheet("style_mobile_other.css"); } }catch(e){ } } }else{ // If it's other device setActiveStyleSheet("style_mobile_no.css"); } function setActiveStyleSheet(filename){ document.write("<link href="+filename+" rel=stylesheet>"); }
Here is the demo page(If you can understand Chinese) : Mobile_demo
Source : http://w3ctech.com/p/1524