How can I detect mobile devices (and/or mobile coo

2019-06-26 08:04发布

We are launching a mobile version of our website very soon. Our full website and mobile website are different only in theme, i.e. URLs are the same, only difference is on the front-end.

We need to be able to do the following when a user visits our site:

1. Check a cookie (mobile == true OR false) to determine if full vs. mobile preference has already been defined (by user manually or by detection on our end).

2. If no mobile cookie is set, detect user's device on first page view and set mobile cookie to true or false.

3. Serve the appropriate experience, full or mobile, based on results of #1 and/or #2.

Initially I was using PHP to detect devices which works fine. However, our site utilizes extreme full HTML caching on the home page and some other pages (.html files are written to a folder in our web root and if Nginx finds them they are served instead of the request going through PHP - cache is cleared every 15 minutes) so I cannot rely on PHP to detect a mobile device from our main point of user entry (as far as I know at this point...).

Not being able to rely on PHP, I then put the mobile cookie check and device detection into the Nginx configuration file (Apache locally for me while developing, translated by our server guy for Nginx). However, our server management folks got back to us saying the performance hit from the new Nginx configuration file would be large (and "performance hit" is a 4-letter word in our office).

Basically I'm being told full HTML caching of the home page has to stay in place and that I can't change the Nginx configuration file at all. Is there another method for cookie/device detection I could utilize given the restrictions in place from above?

2条回答
你好瞎i
2楼-- · 2019-06-26 08:25

You could use javascript.

Try this: http://detectmobilebrowsers.com/

查看更多
Deceive 欺骗
3楼-- · 2019-06-26 08:35

I've used this neat trick with CSS media queries and JavaScript in the past...

Right before your site's closing <body> tag:

<div id="mobiledetect" style="display: none;"></div>

In your CSS file:

@media screen and (max-device-width: 768px) {
  #mobiledetect {
    text-transform: uppercase;
  }
}

In your JavaScript file (depends on jQuery, but you could modify it):

$(function() {
  $is_mobile = false;
  if($('#mobiledetect').css('text-transform') == 'uppercase') {
    $is_mobile = true;
  }
});
查看更多
登录 后发表回答