How to Detect User’s Device Type with JavaScript
Detecting whether a visitor is using a mobile phone, tablet, or desktop computer can help improve the user experience. Whether you want to tailor your layout, load lighter assets, or better understand your audience, JavaScript can offer real-time insights.
Why Detect Device Type?
- Optimize layout for device-specific screen sizes
- Improve site speed and loading for mobile users
- Track user behavior more accurately
How It Works
We can use the `navigator.userAgent` property and check for common patterns:
function getDeviceType() {
const ua = navigator.userAgent;
if (/mobile/i.test(ua)) return "Mobile";
if (/tablet/i.test(ua)) return "Tablet";
return "Desktop";
}
console.log("Device Type:", getDeviceType());
Other Techniques
You can also detect screen width or use libraries like Modernizr or WURFL.js for more precise targeting.
Media queries in CSS or `window.innerWidth` in JavaScript can also support responsive strategies.