[Optimizing webapp] a friend who wants to optimize Mobile front-end should come and check it out.

Source: Internet
Author: User

Single page or multiple pages

This article only represents my point of view. If you have any questions, please forgive me.

Webapp

Xiao Chai has been engaged in single-page-related development for more than a year. During this period, he admired the webapp website model and sorted out many mobile development knowledge points. But now, looking back, it's really hard to say whether webapp is good or not!

The webapp uses JavaScript to modify the page, and then transmits more data from the server and then modifies the page.

From the perspective of performance, in modern browsers, single-page Web apps are comparable to normal native applications, and almost all operating systems support modern browsers.

Therefore, many people think that webapp is the biggest winner in the HTML5 pop-up process. What are the specific characteristics of webapp?

SPA (single page application), a single-page webapp, has the following advantages:

For user experience, you do not need to load the entire page for content changes. In this way, there will be no white pages, and the page can be seamlessly switched to the page, even with a certain animation effect.

The number of requests is small, and the request content does not need to be parsed by the server. This reduces the load on the server and consumes less bandwidth. For example, you do not need to receive the complete html structure each time, but only need json data.

Of course, a single-page application is not flawless, and he has the following problems:

Due to historical reasons, a single-page application does not have good SEO support and requires special processing on SEO.

Loading for the first time is too large and loading for the first screen is slow, so special processing is required for the first screen.

The entry threshold is high. In addition, view encoding needs to release resources to avoid high heap values and high requirements on coding personnel.

Status quo

The legendary webappSufficientCompared with the native app, there is still a long way to go. Xiao Chai expects that this is "enough" to be completed in 2-3 years. So what is the truth?

In fact, there are very few websites in the webapp model on the mobile end. A Taobao app was just half a year ago, but the two days later it saw it changed back. Although Xiao Chai had confidence in the webapp, where did he come from?

Ctrip webapp is unique, where ipad is involved in webapp, but the mainstream websites in China are still traditional websites, mainly for two reasons:

① SEO

② Don't want to eat crabs

So, Ctrip's webapp is very valuable in China. Here, I have to cry out ......

Advantages and disadvantages

The advantages and disadvantages of the webapp are not the disadvantages of Xiao Chai. The stability of webapps is not higher than that of traditional websites. For SEO, webapps require other solutions. For spam, webapps need to release their own resources.

In terms of experience, webapps need to consider loading the first screen; in terms of animation, webapps need to consider low-end mobile phones, so webapps still have a long way to go!

Xiao Chai believes that the current webapp effect is not comparable to that of native apps. One day, when webapps no longer restrict the network and devices, the spring of webapps will not be far away.

Even so, at this stage, webapps will have a lot of optimization tips and tricks to talk about. Here, Xiao Chai will share it with others, hoping to help webapps.

Overview of network transmission optimization

Frontend optimization is divided into two entry points: network transmission and DOM operations, while network transmission is the main factor restricting the speed of a website.

The main point of network transmission optimization is that there is no request and no traffic, which means to minimize the number of requests and reduce the number of requests.

For webapp applications, slow loading of the first screen is an inevitable problem. Therefore, improving the loading speed of the first screen is the key to improving the overall website speed.

Fake page-acceleration of the first screen

It makes people feel much faster.

Reduce the number of requests

For webapp homepage, there are many js files that are inevitable to use. These files are divided into two types:

① Framework js-css

② Js-css of various business teams

Therefore, we can limit that each business team can only load these four files to minimize the number of requests. Parallel loading is involved, and the quantity and capacity have a critical value, you need to experiment on how to obtain this critical value.

Reduce Request volume

Although image compression is unnecessary, sometimes you will find that some websites have a large image size, which must be processed.

Taking the Framework library as an example, in addition to the core package, the UI or function library that is not required can be removed, and dynamic loading can be used to reduce the volume of loading for the first time. This should be done well in the first place, if it is not done well, it cannot be changed later.

Take the business team as an example. The js and html templates loaded for the first time will compress and merge several commonly used pages, and request other pages when accessing them, to load the first screen, you can download only the required page files.

In addition, pay special attention to the following two points:

① If you want the jQuery library, you can switch to zepto.

② Do not reference third-party libraries randomly. If you want to reference a third-party library, you must read the source code and rewrite it. The advantage is that if you have any problems, you can modify it, instead of changing the database.

Cache Ajax/localstorage

The principle of this solution is similar to the previous one. When sending Ajax requests, we should cache some non-real-time data, such as city information and common contacts, but we can only cache non-sensitive information,

The request data from the product search page to the List page is cached for 30 s-60 s. If the user returns to the List page within the expiration time, the data is not requested again.

This is advantageous for the server pressure and page response. In fact, this is of little significance within 30 s and can reduce one request.

In addition, someone has tested the efficiency of get and post:

The average time consumed by get100 times is 323 ms; the average time consumed by post100 times is 589 ms, so the post method is slower than get, but the advantage of post request is secure and there is no length limit on the parameter.

Whether to select post or get must be processed to avoid url truncation or post everywhere. -

Lazyload

Only the first screen page is displayed, and other content needs to be loaded, such as the list page and image lazyload.

DOM operation optimization Overview

DOM operations are mainly divided into page rendering and resource cleanup (heap control). The two complement each other. If DOM operations are not well processed, they will not feel slow, but slow.

Therefore, the main purpose of DOM operation optimization is to eliminate page cards, which is especially important on mobile terminals.

About page rendering

The browser parses three things: HTML, Javascript, and CSS.

The browser first generates a DOM Tree based on HTML, and then generates a CSS Rule Tree based on CSS. javascript can operate the DOM Tree and CSS Rule Tree through DOM APIs and CSS APIs, causing page changes.

The browser will form a render Tree through the DOM Tree and CSS Rule tree after parsing. Only elements whose display is not "none" will form a render Tree. After the render Tree is formed, the browser will call the GUI to draw pages, one thing we did before this was layout or reflow. The above description can be divided into the following steps:

L generate a DOM tree

L calculate CSS styles

L construct a render tree

L reflow: location and size of positioning Elements

L draw a page

In this process, if javascript dynamically changes the DOM Tree, it will cause reflow.

The element changes on the page, as long as the size is not affected, for example, only the color changes will only cause repaint and will not cause reflux.

Otherwise, reflow is inevitable. In this case, re-calculation is required to form a render Tree.

Reflow is divided into local reflux and global reflux, which will affect the following and will not affect the above elements

Reflow consumes a large amount of system resources, and all affected nodes in the DOM Tree reflow. The worst case is that all nodes reflow, this problem is caused by a low-performance computer fan that keeps turning and the phone gets very hot and consumes a lot of power. The following operations may cause reflow

L operate the dom Structure

L Animation

L DOM style Modification

L API for Retrieving Element sizes

Reduce the use of location attributes (fixed/absolute)

When the static element is in the Document Stream, its rendering speed is the fastest. We have done a test:

The rendering time difference between 100 absolute elements and 100 static elements is between 0.01-0.007 ms.

The rendering gap between the 100000 elements increases to about 30 ms. This tiny time difference is particularly evident on the Mobile End, for example:

Xiaomi/SamSung mobile phone (around 1000) has obvious rendering problems, including:

L positioning elements cannot be displayed on mobile phones.

L positioning element animation effect is invalid.

The above problem is caused by the failure of UI rendering, the best solution is to reduce the use of positioning elements, otherwise it can only cause strong reflow to solve.

In addition, there are often fixed-related requirements for products. For example, the PAYMENT button is always at the low end, which may cause two problems:

L The fixed element becomes invalid when it encounters a text box and may float in the middle of the page to block the input.

L Efficiency

Problem 1 is related to the implementation of the mobile terminal. There is no perfect solution for the moment. Problem 2 is directly related to rendering.

During screen scrolling, all pixels on the page will scroll. The video card can quickly move up and down the screen. However, if a fixed element or element does not scroll together, so rolling is a burden for mobile browsers, this scroll performance is even reflected in the iphone 4S, because rolling may cause reflow, this phenomenon is reflected in:

When you use absolute with javascript to simulate the fixed effect, there will be a split effect, and this problem will not occur in iPhone 5S.

Skillful

Of course, we can't ignore the product requirements. The fixed class needs should be solved technically and a good user experience should be given.

Caused by virtual keyboardFixedElement dislocation

The fixed element is always accompanied by the appearance of the virtual keyboard, but the virtual keyboard is only "pasted" on the viewport, and does not have "any" impact on dom on the surface, however, in this case, the performance of the fixed element becomes odd and misplaced.

The application-level solution is to set the fixed element to static when the virtual keyboard pops up, and set it back when the virtual keyboard disappears.

Because the virtual keyboard does not throw an event, but the scroll or resize event detection may have a certain delay and will flash, therefore, the best solution is to use the setinterval timer to monitor whether the currently obtained focus element is a text element. If so, you need to handle the issue so that the fixed element error can be solved.

FixedElement sliding inertia Smoothness

We often encounter this kind of product requirement. The tab bar starts to be fixed. When the scroll down beyond this tab bar, it will become a fixed element and will always appear in the header, there is no problem with such a requirement on the computer, but mobile phones below iPhone5s may often suffer from small-range misplacement or large-scale misplacement of Fast movement.

At this time, we can cause reflow to force the browser to redraw to solve this problem. Here we recommend a strange hack statement: Set the src attribute of the three image elements at the same time, the problem can be solved in a wide range. The solution was confirmed and applied by the team.

// Three-image src, which triggers reflow and handles inertia issues of the fixed solution

Var el = this. els. ctlc. find ('img ');

$ (El [0]). attr ("src", 'HTTP: // res.m.ctrip.com/html5/Content/images/144.png ');

$ (El [1]). attr ("src", 'HTTP: // res.m.ctrip.com/html5/Content/images/144.png ');

$ (El [2]). attr ("src", 'HTTP: // res.m.ctrip.com/html5/Content/images/144.png ');

In addition, the blue line under the tab has an animation, but it may not move On Xiaomi or Samsung mobile phones. This can also cause dynamic reflow to solve this BUG.

Others

L The CSS selector tries its best to use id and class to avoid excessive cascade.

L avoid using numeric values. For example, border: none does not cause rendering, while boder: 0 does.

L extract elements from the Document Stream during animation to avoid leading to a large number of reflows

L avoid modifying DOM styles one by one, and use className to implement the same function

L set the display to none when operating the DOM, because this element does not affect rendering, or the fragment object is used to replace the DOM displayed on the page.

L avoid repeated reflow operations when getting DOM style attributes in a loop

Memory Resource Optimization mobile javascript

First, the performance of the mobile terminal and the performance of the PC end are not in the same order of magnitude. For example, my brother did a test and used innerHTML to draw a large segment. Then he wanted to get the ID node of HTML, in fact, it cannot be obtained. This problem often occurs when multiple pages are simulated on a single page and DOM is dynamically created.

Var element = $ ('<div id = "test">... a large number of structures... </div> ');

Contents (root).html (element)

$ ('# Test) // null

This type of problem is incredible because page UI rendering and DOM operations are mutually exclusive, but even if this problem occurs, a solution is to use settimeout, A better solution is to use the DOMNodeRemoved event to monitor page DOM changes and put our DOM operation callback to ensure that the rendering ends.

The above problems are just to illustrate the performance problems of mobile terminals. These performance problems will lead to many inexplicable problems, and many problems are related to rendering. However, this also shows the shortage of resources on the mobile end. If the heap value is too large, the operation may become stuck. What's more, the page may be suspended and exited directly.

The webapp mode is completely dependent on the garbage collection of the browser, basically it is dead, because once a traditional page is refreshed, the entire page resources are completely released, and webapp does not refresh such operations, there is only one status to two. Unrelated memory is retained, resources must be manually released, or the framework must provide a mechanism for garbage release.

This is clearly indicated by the heap value change in the chart.

In the view switching process, if the unused resources are not manually set to null, the variable cannot be recycled, and it is out of framework control and out of control. Therefore, we need to pay attention to the following during the webapp process:

L release unused closures

L The Observer needs to be cleared.

L release Timer

L release view-related resources in destroy during view switching

-- Thank Alan for his support.

Closure trap

During our work, misuse of local variables is very likely to cause the closure trap. This problem is not only a performance problem, but may cause errors logically and is not easy to find. For example, use a local variable in the AMD Closure

Var _ attributes = {};

Callback ($. extend (_ attributes, opts ));

In this case, the _ attributes object will be changed. If an instance is normal, variable contamination will occur for the two instances.

This is just an example, but misuse of local variables in the Code may cause unnecessary worries and caution.

Release webapp Resources

Based on the previous descriptions, we can draw a conclusion:

Whether it is a view or UI component, we must provide a unified destroy interface to allow users to inherit and release resources.

If the view resources are not released, the heap value is too high, and the value of the webapp website is greatly reduced. Here are some considerations:

L no more than five view instances are saved in the webapp. When more view instances are saved, the dom structure and memory reference are released (the critical value is the best)

L release internal resources when the view is hidden and remove the DOM Event handle

L The UI component is the same as the view component and must be released in a unified manner.

However, because a single-page application does not refresh the page, there are always some resources that cannot be released, which is a long way to go. You can optimize the preparation process as follows:

L use function replacement Logic

Let our function generate a return value to replace the large logic in the function. The first advantage is that the logic is clear, and the second advantage is that these functions are in different functions, when this function is used, it is automatically released.

L clear closure references

When a closure function or when it is used, if it is not used again, you need to manually clear the variable to remove the reference relationship between the closure and release resources.

L use object attributes or methods

An object can reference the attributes or methods of other objects, such as obj. foo = thatObj. In this case, we can delete the object from the reference relationship at any time and then clean up the resources.

Animation and animation

We recommend that you use CSS3 for animation, and the latest interface is recommended in CSS3. For example, you can use transform to replace top/lelf operations, which is much more efficient.

If an animation is used, the corresponding element can be set to absolute to reduce reflux. The most important aspect is

Avoid moving too many nodes in the DOM tree. In this case, you need to reject unreasonable requirements of the product, such:

The product requires the date scrolling component to display data for six months. The data for these six months is 180 DOM trees.

Once a mobile phone moves the DOM at this level, the entire mobile phone will be stuck, and even the DOM tree will be built to render the page. This problem needs to be avoided.

Application Cache

Application Cache is an API added by HTML5 for offline use of webapps. Unlike localstorage and cookies, Application Cache stores a series of request resources that allow browsers to request resources without passing through the network, offline applications can be implemented after proper design.

Application Cache improves network performance, effectively reduces network latency, and improves request acceleration.

For example, the new version of the cache does not take effect immediately; the Request Path in manifest is relative to the manifest file, rather than loading the page; updates/rollback and other issues, so whether to use it or not must be demonstrated.

Experience optimization area rolling

Mobile Terminals often need to implement regional rolling. Mature IScroll solutions are also available, but the solutions are not ideal.

In the official example, the following problems will occur:

L The header disappears.

L occasionally, the text box focus cannot be displayed, or the focus is misplaced.

If the above problem is ignored, but the text box is missing, I will not accept it.

The cause is related to the default browser events of the organization. Therefore, I do not recommend that you use area scrolling in a wide range, but use it in a region,

The ipad version where I went used IScroll in a text box. The improved user experience is as fascinating as the problem.

As a matter of fact, Xiao Chai and his IScroll database have such problems,,IScroll is the library most likely to bring about the mobile revolutionBecause he can:

① Solve webapp area scrolling

② Solve the fixed problem in disguise

③ Solve the problem of long and short pages in the animation process

All in all, the proposal of the IScroll solution is to bring webapps closer than native apps, and the true stability still requires support from browsers.

Click response

There is no problem with the click response on the mobile end, but the latency of 300 ms is a fact. The reason for this is that

The mobile phone needs to know if you want to double-click to enlarge the webpage content

Therefore, the click response is slow, but touch does not have such restrictions, so touch on the Mobile End is quite popular. How slow is the mouse speed, I will tell you that it will take 300 ms every time

So the problem needs to be dealt with, see: http://www.cnblogs.com/yexiaochai/p/3462657.html#_h2_7

Conclusion

Webapp is not a matter of two days a day. One day, webapp will bloom its own style!

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.