Jump to content

A better way to detect mobile devices


Recommended Posts

Hi Guys. Currently, Invsion Community displays the code for mobile devices using @media screen, which is ok, but it only seemingly hides the code because it is still in the source.

Being on the desktop, the code for mobile devices is unnecessarily loaded.

Why not use PHP for mobile device detection? This code is just an example, but it shows that it can be done in a simple way.

//-- Very simple way
$useragent = $_SERVER['HTTP_USER_AGENT']; 
$iPod = stripos($useragent, "iPod"); 
$iPad = stripos($useragent, "iPad"); 
$iPhone = stripos($useragent, "iPhone");
$Android = stripos($useragent, "Android"); 
$iOS = stripos($useragent, "iOS");
//-- You can add billion devices 

$DEVICE = ($iPod||$iPad||$iPhone||$Android||$iOS);

if (!$DEVICE) { ?>
<!-- What you want for all non-mobile devices. Anything with all HTML, PHP, CSS, even full page codes-->
<?php }else{ ?> 
<!-- What you want for all mobile devices. Anything with all HTML, PHP, CSS, even full page codes --> 
<?php } ?>

This would bring many benefits because being on a mobile device (or on a desktop), we would only load the code that is needed, excluding the one that is unnecessary. This would reduce the weight of the html file and improve the speed.

Edited by SeNioR-
Link to comment
Share on other sites

There is nothing simple or better about it. It’s just unreliable. What if use a smaller browser window on desktop? The site would break since it can’t be displayed properly. Because with your method, the code for smaller screens would have been removed. What if PHP can’t detect the device clearly for some reason? Again, the site could break because the wrong version could be delivered. 

All in all, the benefits of stripping a few lines of unused code don’t outweigh the potential negative consequences. After all, it IS about the screen size, not the “type” of device. The break points are called “desktop”, “tablet” and “mobile” but that is just a convention. The device doesn’t really matter, so recognizing it isn’t the point. It must work for whatever screen size is available and that is something determined (and possibly even changed) on the client side. 

Link to comment
Share on other sites

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...