Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WAP中Loading图加载策略 #4

Open
tjuking opened this issue Sep 14, 2015 · 0 comments
Open

WAP中Loading图加载策略 #4

tjuking opened this issue Sep 14, 2015 · 0 comments

Comments

@tjuking
Copy link
Owner

tjuking commented Sep 14, 2015

以下内容只针对页面加载时的动态图片loading效果的加载策略优化,对于完全CSS控制的加载效果可以不用考虑。

另外对于需要及时给用户展现的大体积图片,并且存在多个页面都有出现该图的情况也可以考虑使用以下的加载策略。

用户体验

loading图的作用是提醒用户页面正在加载过程中,需要等待。如果我们使用正常的图片请求,就会有多一次的请求往返和下载消耗,对于WAP中第一次访问的用户来说用户体验就不够好。例如下面所示代码:

.loading{
    background: url(http://www.x.com/image/loading.gif) no-repeat center center;
}

所以优化策略是给首次访问的用户以内联的图片(base64编码),以达到及时解析展现给用户最快的交互反馈。例如下面所示代码:

.loading{
    background: url(data:image/gif;base64,R0lGODlhAwADAIABAL6+vv///yH5BAEAAAEALAAAAAADAAMAAAIDjA9WADs=) no-repeat center center;
}

性能优化

如果在每个WAP页面中都内联这样加载的loading图,就无法利用缓存图片的优势,也是在浪费用户的宝贵流量。

所以我们要对上述方案进行改进,对loading图进行缓存控制,增加一个cookie标识位"loading_gif"用来识别是否已经加载过该图片。

加载策略可以简化为下面所示代码:

{%* 没有缓存时 *%}
{%if !$smarty.cookies.loading_gif%}
    <style>
        .loading{
            background: url(data:image/gif;base64,R0lGODlhAwADAIABAL6+vv///yH5BAEAAAEALAAAAAADAAMAAAIDjA9WADs=) no-repeat center center;
        }
    </style>
    <script>
        window.addEventListener("load", function(){
            var img = new Image();
            img.onload = function(){
                var date = new Date();
                date.setTime(date.getTime()+365*24*3600*1000);
                document.cookie = "loading_gif=1;path=/;expires=" + date.toGMTString();
            };
            img.src = "http://www.x.com/image/loading.gif";
        }, false);
    </script>
{%* 有缓存时 *%}    
{%else%}
    <style>
        .loading{
            background: url(http://www.x.com/image/loading.gif) no-repeat center center;
        }
    </style>
{%/if%} 

版本控制

如果设计师或产品对loading图进行升级怎么办?不用担心,我们可以对上述代码再做一个简单的升级——支持版本控制。

只需要将Smarty的判断条件调整为判断版本号并且在设置cookie的位置也要更新相应的版本号,例如下面所示代码:

{%if $smarty.cookies.loading_gif != 2%}
...
document.cookie = "loading_gif=2;path=/;expires=" + date.toGMTString();

存在的问题

  • 首次访问用户实际消耗了将近两张loading图片的流量(内联和普通加载);
  • 缓存图片与否不一定和cookie标识位完全对应,例如用户或浏览器可能清除了图片缓存或者触发了强制刷新模式;

个人认为这两个问题都可以接受,如果各位看官有更好的优化方式,欢迎探讨~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant