简体   繁体   中英

PHP, JavaScript - Is it right to detect screen-width by redirecting header

I am using the following JavaScript to detect the screen-width and use it as a constant across my template files through conditional statements to display / not-display portions of my site. While it has nothing much to do with my questions, but just in case... Yes I am using WordPress. Also I am already using mobiledetect PHP Library.

function getLayoutWidth() {

        if (isset($_GET['width'])) {
          define( "SCREEN_WIDTH", $_GET['width']);
        } else {
          echo "<script language='javascript'>\n";
          echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
                        . "&width=\" + screen.width;\n";
          echo "</script>\n";
          exit();
        }
    }

Important :

  1. Other techniques are like...... Let's assume if my site is 2MB in size, it will still load 2MB of content and then hide 1.5MB of it on mobile devices by using CSS properties like display:none; Whereas I don't want that template part to load itself, thus not needing to hide anything.

  2. I am not looking to load an entire JavaScript library like jQuery or so to do this because location.href=\\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}". "&width=\\" + screen.width; location.href=\\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}". "&width=\\" + screen.width; is the only JavaScript in my entire site. Rest everything is pure PHP, HTML and CSS based. I even disabled jQuery of WordPress in the front-end template.

UPDATE : Since some friends did not get my point although I mentioned clearly that I don't want to load the content into DOM at all, I am giving a bit more clarity here.....

For Example --- @1200px I want only 1 Sidebar to be displayed. @1600px I want 2 Sidebars to be displayed and over 1600px I want 3 Sidebars to be displayed. Please don't suggest Media Queries solutions as I already know it and that is exactly what I don't want to do. I want to avoid loading the content into DOM. Kindly let focus be only and only on questions asked. Also please don't post suggestions as answers. Let others with proper answers do it. Kindly post suggestions in Comment section.

My questions :

  1. Is this a good / correct way to do from SEO stand point? If not why?

  2. My URL is displayed as example.com/my-product-category/my-product-name/?width=1440 How to remove /?width=1343 and display just example.com/my-product-category/my-product-name part?

Simple answer, no, it is not good from a SEO standpoint. Or any other standpoint. Crawlers such as Googles are designed to completely ignore all hidden elements and thus you will lose big time SEO ranking if your content isnt getting fully crawled, and crawlers crawl each site multiple times masquerading as mobile devices to check if the site is mobile friendly as well. http://www.seonick.net/responsive-design-seo/

Not to mention the trouble of calculating your arbitrary cutoff point of .5mb serves no purpose if the content is merely hidden (since its all getting sent anyway thus saving no bandwidth).

You need to do this in pure CSS using media queries, it is the most compatible way and allows for a fluid design (changes on the go as the window resizes.

<link rel="stylesheet" media="(max-width: 700px)" href="mobile.css">
<link rel="stylesheet" media="(min-width: 700px)" href="full.css">

That will use one css file if the window is smaller than 700px and the other if it is over.

Another of my more favorite methods is to use the http://mobiledetect.net/ class. Its small and fast, more accurate and better flexibility. Load that class then just add classes to your body element depending on the visitors browser

<body class="<?PHP if ($detect->isMobile() && !$detect->isTablet()) echo " .phone";?>">

Then style by targeting classes inside body.phone . This method also ensures you know if the browser is mobile BEFORE the DOM starts to process, meaning you can serve compressed versions of images through some simple logic rather than having CSS swap them out or just resize them or omit entire parts of the markup from being sent to the user at all ensure bandwidth is only used for parts of the DOM relevant to the users device.

<body>
This is normal content and will be visible to all devices
<?PHP if (!$detect->isMobile()) { ?>
This content will only be visible to desktop users, in fact it wont even be transmitted to mobile users thus making it NOT in the DOM
<?PHP } ?>
</body>

To set a cookie in javascript

function Cookies(){};
Cookies.prototype.save=function(name,value,days){
    if( days ) {
        var date = new Date();
        date.setTime( date.getTime()+( days*24*60*60*1000 ) );
        var expires = "; expires="+date.toGMTString();
        var dom = "; domain="+document.domain;
    } else { expires = ""; }
    var path = "; path=/";
    var tmp=[];
    if( typeof( value )=='object' ) {
        for( p in value ) tmp.push( p+'='+value[ p ] );
        value=tmp.join(';');    
    }
    document.cookie = name+"="+value+expires+path;
};
Cookies.prototype.read=function(name){
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for( var i=0; i < ca.length;i++ ) {
            var c = ca[i];
            while( c.charAt(0)==' ') c = c.substring(1,c.length);
            if( c.indexOf( nameEQ ) == 0 ) return c.substring( nameEQ.length, c.length );
        }
        return null;
};
Cookies.prototype.erase=function(name){
    this.save( name, "", -1 );
};



var cn='jsdim';
var ckie=new Cookies;
ckie.save( cn, JSON.stringify({ width:screen.availWidth, height:screen.availHeight, colour:screen.colorDepth, depth:screen.pixelDepth }), 1 );

In PHP

<?php
    if( isset( $_COOKIE['jsdim'] ) ){
        $json=json_decode( $_COOKIE['jsdim'] );
        if( !defined('SCREEN_WIDTH') ) define( 'SCREEN_WIDTH', $json->width );
        if( !defined('SCREEN_HEIGHT') ) define( 'SCREEN_HEIGHT', $json->height );
        if( !defined('SCREEN_COLOUR_DEPTH') ) define( 'SCREEN_COLOUR_DEPTH', $json->colour );
        if( !defined('SCREEN_PIXEL_DEPTH') ) define( 'SCREEN_PIXEL_DEPTH', $json->depth );
    }
?>

I do not think, that screen size/resolution is really what you want to adjust your view templates for mobile devices. Actually you want to know what plattform/device someone is using, think about Nexus 7, which has 1920 × 1200 or Sony Xperia Z5 with 2160 x 3840px.

I would look at user-agent and HTTP headers for the server side code, there are already good libraries for that: eg mobiledetect . For the client side the best practice is to use CSS3 Media Queries: Media Queries for Standard Devices

You can retire the $_GET of the URL by the htaccess, I'm using RewriteRule .

Options +FollowSymLinks
RewriteRule ^folder/file.php$ folder/file.php?g=2
#if you want to remove php file extension, don't keep the .php before the $

To remove all php files extension: php.net .

Edit: this is for who doesn't use Wordpress

You can use this plugin: https://wordpress.org/plugins/mobble/ It adds an is_mobile() -feature.

In your theme you can now use is_mobile() instead of $_GET['width'] > ... This way you don't need a ?width= in your $_GET

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM