项目新的需求,网页的自适应交付/响应式交付 Responsive/Adaptive Delivery

网页为什么要做自适应交付,皆因现在移动设备大行其道,现在是移动互联网时代,以IOS及Android为首的各种移动终端已经遍地开花。

当人家用380px的iphone打开你的网页时,你总不能显示个1024px的页面给人家,用户体验大打折购,因为响应式设计或者自适应交付就应运而生。

之前已经提到过响应式设计(responsive design),但响应式设计有个重点就是不管3721,全部资源(html,css,js)统统加载下来,页面比较冗肿;而响应式的交付,完美的响应式交付是服务器跟据访问者的设备终端,动态交付相应html、css、js资源,全部是实实在在的东西,没有多余的代码或者资源。经测试ASP.NET MVC 4及往后版本可以轻松实现此功能,模版页面命名方式加多个.mobile就可以,当然服务端动态response.write也可以动态拼了页面,但工作量大啊!后端人家也不肯……。

无奈,项目紧迫,说服PM用的目前比较流行的伪响应式交付的方式,用页面的重定向(redirect) 与页面cookie控制相结合

需求:

一、设计2套模版,一个是平板电脑/桌面端 模板(www.yoursite.com),另一个是手机端(www.yoursite.com/mobile 作为子站) 模板,关键是设好手机版的Viewport的宽度如下因为所有的移动终端会根据你的viewport来自适应显示。

<meta name="viewport" content="width=400">

  

二、响应式交付

full site页面顶部加入如下JS代码

var useragent = window.navigator.userAgent.toLowerCase();
var currenturl = window.location.href.toLowerCase();    
var targetSite = getCookie('targetSite');

if (targetSite == '' || targetSite == null || targetSite == 'mobile')
{
    if(useragent.indexOf('ipad') == -1 && useragent.indexOf('mobile') != -1)
    {
        {
            var newUrl = currenturl.toLowerCase().replace('www.yoursite.com', 'www.yoursite.com/mobile');
            setCookie('targetSite', 'mobile','/');        
            if (currenturl.indexOf('/mobile/') == -1) {
                window.location.href = newUrl;
            }
         }      

     }
}
/*****
cookies
 *****/
function setCookie(name, value, path) {
    var date = new Date();
    date.setTime(date.getTime() + 0.5 * 24 * 3600 * 1000);//cookie lasts half of a day.
    var p = "";
    if (path) {
        p = ";path=" + path;
    }
    document.cookie = name + "=" + escape(value) + ";expires=" + date.toGMTString() + p;
}

function getCookie(name)
{
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null)
        return unescape(arr[2]);
    return null;
}
function delCookie(name)
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

在mobile site,相应要有选择跳到full site的链接,那要加上cookie控制

function redirectFullUrl() {
    var currenturl = window.location.href.toLowerCase();
    delCookie("targetSite");
    setCookie("targetSite", "full", "/");
    var newUrl = currenturl.toLowerCase().replace('www.yoursite.com/mobile', 'www.yoursite.com');
    window.location.href = newUrl;
}

这样就OK啦,原理比较简单,主要通过控制cookie来引导,当然你full site与mobile site的页面所有相应要严格对得上

原文地址:https://www.cnblogs.com/fastmover/p/3868735.html