Mobile-H5 active page optimization scheme

Source: Internet
Author: User
Tags lua nginx server

Background

Project : Mobile H5 e-commerce Project
Pain point : Slow!!!
Initial Scenario : The most basic picture lazy loading, static resources put into cdn,predns and so on have been done. But it's still slow, where's the slow?
obvious reason : due to the separation of the front and back end, all the data are issued by the interface, and then render the page according to the template. In other words, we need to first load JS, wait until the JS loaded, request the interface, the interface returns data, render the page, load pictures and so on. Although the use of modular loading method, but for the high-demand home page and active pages, the user's perception is not very good.

First edition Solution

Initially, due to time constraints, basically from the client to optimize processing, basically can be summed up in the following aspects.

One, local cache

We do a local cache optimization strategy, the first request after the interface data cache into the Localstorage, and storage time, set the expiration time, generally set to 5 minutes, the user in 5 minutes to open the page repeatedly, do not request the interface again, Fetch the data from the Localstorage and render the page directly.
Follow-up simply the template rendered good HTML fragments stored up, directly splicing, eliminating the time of the template calculation.
The basic implementation scenario is as follows:

varCache= Localstorage.GetItem(' Cache '),Expires= 5 *  - *  +;//Decide whether to expirefunction Isoverdue(Pasttime,Expires{    return Date. Now()-Pasttime>=Expires;}if(Cache&& !Isoverdue(Cache. Time,Expires)){    //Indicates that the cache exists and is not expired    //make corresponding rendering for normal fetch cache.data} Else {    //Indicates that the cache does not exist or has expired    //re-request interface    $.Get(' a.cn ', Funciton(RES){        //Do something        //After the corresponding render operation is processed, the data is cached and the current time is recorded        Localstorage.SetItem(' Cache ', {            Data:Res,             Time: Date. Now()})})} 

However, it is not enough that the new user will not be able to open the page for the first time, and when the user reloads after 5 minutes, there is still a delay (because the browser caches a portion of the static resources, which is not as slow as when the user first opens).

Ii. further caching of static resources

In the daily development, there are many dependent libraries, common fastclick,swipe and so on, these libraries, there is no need to load each time, although the browser will do some static resources cache, but can not be completely controlled by us, so, these infrequently changed static resources are cached, the same, To Localstorage inside.

Need to be aware

There is a problem with this scenario, and if the script tag is loaded directly, it cannot be directly taken to its scripting content.

<script id="script1" src="js/jquery.js"></script>
console.log(document.querySelector(‘#script1‘).innerHTML);// 此时输出的是undefined,因为innerHTML是获取标签内容,此时script标签里并没有内容。
<script id="script2">console.log(‘2‘);</script>
console.log(document.querySelector(‘#script2‘).innerHTML);// 此时输出的是console.log(‘2‘);// 因为innerHTML是获取标签内容,此时script标签里并没有内容。

This is certainly not what we want, we need to be outside the chain JS executable code.

Two schemes for adding JS dynamically

I mentioned two scenarios in my previous high-performance JavaScript reading notes.

1. Dynamic Scripting elements
var  script =  document . createelement  ()  script . type  =   ' Text/javascript '   script . onload  =  function  () { //do something  }   Script . src  =   ' jquery.js '   document . getelementbytagname  ( ' Heda ' ) [0 ]. appendchild  (script)   

This method can monitor the completion of the script, but it is not possible to get the JS code we want by adding a script tag.

2. Via XMLHttpRequest Script injection
varXhr= New XMLHttpRequest();XHR.Open("Get", "File1.js", true);XHR.onreadystatechange = function(){    if(XHR.readyState == 4){        if(XHR.Status >=  $ && XHR.Status <  - || XHR.Status == 304){            Localstorage.SetItem(' File1 ', XHR.ResponseText);        }    }}

It is important to note that this method has a cross-domain risk, so we need the allow-origin of the static resource server to be set to *. or directly load the JS under this domain name.

There are classmates to ask, since localstorage so strong, why not all the things are cached up?
Of course, because of its limited size, in Firefox and Chrome, generally speaking, sessionstorage and localstorage size is 10MB, while Safari is only 5MB. See this article for more details.
This limits the idea of what we have in store. If the pictures are small, you can cache them.

Second Edition Solution

In the previous version of the scheme, we solved the slow problem of subsequent loading, in the subsequent page opening speed, basically can be opened second.
However, this solution is still insufficient, for the new user experience is not very good, if users at this point in 5min open, the speed will be reduced.
Finally, we can only do SSR.
There is a problem, why is it now popular server rendering HTML?
There are many benefits to server-side rendering, and the biggest benefit for us at this point is that the page is straight out. This step is omitted for the request interface. And it's good for improving the user experience.
If there is enough time, you can use node to do the service, but for historical reasons, our project is also relatively time-consuming, so we finally decided to use Openresty.
Openresty Tutorial Online A lot of, I also do not say, in addition to the official Git, recommended open-Tao blog learning.

Whether we are on the client interface data, or the server, the activity page data generally have a certain duration, that is, we can also make a cache on our Nginx server, assuming that a user visited an activity, in the next five minutes, Any other user (under the same permission) has access to the cached page when the first user accesses it.

LocalArgs=Ngx.Req.Get_uri_args()LocalAcId=Args[' AcId ']LocalKey= ' AC ' ..AcIdLocalExpire= 5 *  - --cache time 5 minutesLocalValue=Dict.GetData(Key,Expire)if  notValue Then    LocalRes=Ngx.Location.Capture('/a.json ')    ifRes.Status==  $  Then        --Dict is a script to handle the storage and reading logicDict.SetData(Key,Res.Body)    ElseNgx.Say(Dict.GetData(Key))    EndElse    --Ngx.log (4, type (value))Ngx.Say(Value)End

In Dict, we can convert the interface data into HTML fragments and store them through templates. In this way, the user will not feel slow after the first time they enter our page.

What ' s more

What openresty can do is not only these, but also some of the controls on the gateway's permissions can be implemented with it.
The above two solutions also have some shortcomings, such as the first screen may be more content, once loaded over, not necessarily fast. The intuitive first screen is rendered by the server, and for unimportant content, it can be loaded asynchronously via Ajax.
How to calculate the active page such as how large the first screen, how to organize the code, which parts of the service-side rendering, which uses Ajax. These problems also need to be considered in practical development.
Limited time, this is not a better solution to this problem, in the future development, will continue to improve the active page optimization program.

Mobile-H5 active page optimization scheme

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.