JS code to check different mobile devices

Summary

A JavaScript snippet offers a solution for dynamically loading device-specific CSS to address cross-device compatibility challenges. It utilizes `navigator.userAgent` to detect various mobile platforms, including Android, iPhone, iPad, and other mobile devices. Based on the detected environment, a corresponding stylesheet (e.g., `style_mobile_a.css` or `style_mobile_iPad.css`) is injected into the document. This method aims to simplify responsive design by serving tailored styles for different mobile browsing experiences.

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

JAVASCRIPT MOBILE DEVICE DETECTION

  RELATED

  COMMENTS

0

No comment for this article.