"WebApp optimization" to do mobile front-end optimization friends come in and see.

Source: Internet
Author: User

Single page or multiple pages

This article only represents a personal point of view, insufficient please forgive me, welcome to enlighten.

WebApp

Little message engaged in a single page related development more than a year, during the incomparable respected WebApp site model, also organized a lot of mobile development knowledge points, but now back to see, WebApp is good or not really long story yo!

WebApp uses JavaScript to modify the page, then passes more data from the server and then modifies the page, so it loops.

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

So, many people think that WebApp is the biggest winner in the HTML5, so what is his specific?

SPA (Single page application), which is WebApp, has the following advantages:

User experience, there is no need to load the entire page for content changes. This will not appear in the white page situation, the page and the page seamlessly switch, even with a certain animation effect.

Less requests, no server parsing of the requested content, less stress on the server, less bandwidth consumption, such as no need to receive the full HTML structure each time, but only JSON data.

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

Due to historical reasons, single page application to the SEO support is not too good, need to do special processing of SEO.

The first load is too large, the first screen loading is slow, so the first screen needs to do special processing.

The entry threshold itself is high, coupled with the view code needs to release resources to avoid the heap value is too high, the requirements of the coding staff.

Present situation

The legendary WebApp is comparable to the native app, in fact this is enough to have a large distance, the message is expected to be "enough" to fill in 2-3 years, so what is the truth?

In fact, Mobile WebApp model of the site is very few, a half a year ago or, the two days a look and change back, the message although the WebApp have confidence, but where does confidence come from?

Ctrip WebApp Unique, where the ipad to intervene in WebApp, but the main domestic web site is still a traditional site, mainly because of two reasons:

①seo

② don't want to eat crabs.

Therefore, Ctrip's webapp in the domestic, how valuable, speaking here, I will cry out ...

The merits of the points

Better or worse is a small message can be judged, stability, webapp than the traditional site; Seo,webapp needs other solutions; saying garbage collection, webapp need to free up resources.

Said experience, WebApp need to consider the first screen load, said animation, WebApp to consider low-end mobile phones, so WebApp still have a long way to go!

Xiao Chai believe, now the WebApp effect can not be comparable to native app, one day, when WebApp no longer restricted to the network, equipment, then WebApp Spring will not be far.

Even so, at this stage WebApp will also have a lot of optimization experience, artifice can come out to say, here to do a message to share, hope can be helpful to WebApp's classmates.

A survey of network transmission optimization

Front-end optimization is divided into two pointcuts: Network transmission and DOM operation, while network transmission is the main factor restricting the speed of a website.

The optimization point of network transmission is that 0 requests, no traffic , it means to minimize the number of requests, reduce the volume of requests.

For the WebApp mode application, the first screen loading slow is an unavoidable problem , so to improve the WebApp first screen loading speed is the key to improve the overall website speed.

Fake page-First screen acceleration

The above is a homepage of the loading time, we take its 150kb and 30kb speed of loading, you can see slow! If he's webapp, we can do some optimizations.

We should avoid the page long time white page, this time put forward the concept of fake page. Page rendering requires only the full HTML and CSS, and this is the first optimization point.

From the number of data requests and the amount of requests, the response of the WebApp home page should be slow, if the JS loading to complete the rendering of pages, users are likely to lose patience.

But from the domcontentloaded view, the homepage in fact, the page response is relatively rapid, so this loading end of the first screen will render the end, and then asynchronously loaded JS, when JS changes and then dynamically change some key points in the DOM structure

This time a static HTML page, loading the basic content of the first screen, so that the home page quickly display

Then JS loading will immediately re-render the entire page, this way, users can quickly see the page response, give users a quick illusion, give people feel much faster.

Reduce the number of requests

By WebApp homepage, the inevitable use of JS files, these files are divided into two categories:

① Frame Js-css

② various business teams JS-CSS

So can limit each business team will only load these four files, in order to minimize the number of requests, here is related to parallel loading, quantity and capacity has a critical value, how to take this critical value you need to experiment

Reduce Request Volume

Although the picture compression is needless to say, but there are always some times you will find some of the site's image size is very large, this need to deal with, and must deal with.

Take the framework library as an example, in addition to the core package, the unnecessary UI or function library can be removed, using the dynamic loading, reduce the first load, this is done well at the beginning, not good late to change

Take the business team as an example, the first load of JS and HTML template will be commonly used to merge several pages, the other pages to request, if you want to upgrade the first screen loading can only download the required paging file.

In addition, the following two points are particularly important to note :

① If you want it or the jquery library, you can consider switching to zepto.

② do not arbitrarily cite third-party libraries, if you want to quote must be read and understand the source of the case of rewriting the use of, such a benefit is, eat thoroughly, in case there is a problem, can change, and not have no way to change the library

Cache Ajax/localstorage

This scheme is similar to the previous one, when we send 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 caches the 30s-60s, and the data is not re-requested if the user returns to the list page within the expiration time

This to the server pressure, the page response is advantageous, this in the 30s is in fact insignificant, can reduce a request.

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

Get100 times the average time-consuming 323ms;post100 times is 589ms, so the post method is slower than get, but the advantage of the POST request is security, and the parameter has no length limit.

Whether you choose post or get, you need to deal with it, avoid truncating URLs, or post everywhere. -

Lazyload

Only display the first screen page, other content needs to be loaded again, such as List page, picture lazyload, all need to do

A review of Dom operation optimization

Dom operations are mainly divided into page rendering and resource Cleanup (heap control), the two are complementary, if the DOM operation a piece of processing is not good, the resulting feeling is no longer slow, but the card

So the main purpose of DOM operation optimization is to eliminate the problem of page cards, which is particularly important on the mobile side.

about page Rendering

Browsers will parse three things: HTML, Javascript, CSS

The browser will first generate DOM tree based on HTML, followed by CSS rule tree,javascript, which can manipulate DOM tree and CSS Rule tree with the DOM API and CSS API, causing the page to change.

Browser parsing ends with the DOM tree and CSS Rule tree form the render tree, only the display is not a none of the elements will form the render tree, the browser will invoke the GUI drawing page after the render tree is formed , one of the things that was done before is layout or reflow. The above description is simple enough to be divided into the following processes:

L Generate DOM Tree

L Calculate CSS Styles

L Build the Render tree

l Reflow, positioning element position size

L Draw Page

In this process, if JavaScript dynamically changes DOM tree, it will cause reflow

The elements in the page change, as long as they do not affect the size, such as just color changes will only cause repaint will not cause reflux

Otherwise, reflow inevitably, this time will need to recalculate the formation of the render Tree

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

Reflow consumes more system resources, the affected nodes in DOM tree will be reflow, and then the worst case is that all nodes reflow, the problem is caused by the low performance of the computer fan constantly turn, the phone becomes very hot, and very power consumption, The following actions may cause reflow

L Manipulating the DOM structure

L Animation

L DOM Style modification

• API to get element dimensions

reduce the use of positional properties (Fixed/absolute)

The static element is in the document flow and renders at its fastest speed, and we have done a test:

100 absolute elements render with 100 static elements time difference in 0.01-0.007ms

The 100,000-element rendering gap increases to around 30ms, and this tiny jet lag becomes particularly noticeable on the mobile side, such as:

Xiaomi/Samsung mobile phone (around 1000), there are obvious rendering problems, the specific performance is:

The positioning element cannot be displayed on the phone.

L Invalid position element animation effect.

The problem is that UI rendering is much more ineffective, and the best solution is to reduce the use of positioning elements, or it can only cause strong reflow to resolve.

In addition, products often have fixed related requirements, such as the payment button has been on the low end, this demand will cause two problems:

Fixed element fails when encountering text box, may float to the middle of the page block input

L Impact Efficiency

The problem is related to the implementation of the mobile side, there is no perfect solution for the moment, problem two is directly related to rendering

Scrolling, all the pixels on the page will follow the scroll, the graphics card on the full screen to move up and down the processing quickly, but if there is a fixed element or the element does not follow the scroll, then the mobile browser is a load, the scrolling performance even reflected in the iphone 4s, Because scrolling can cause reflow, this phenomenon is reflected in:

When using absolute with JavaScript to simulate a fixed effect, there is a fragment effect, and this problem does not occur in iphone5s.

Artifice

Of course, we can not ignore the demand for products, fixed-class requirements should be technically resolved, but also the user a good experience.

virtual keyboard causes fixed element Dislocation

Fixed elements are bound to accompany the advent of the virtual keyboard, but the virtual keyboard is simply "pasted" on the viewport, the surface will not have "any" effect on the DOM, but this time the fixed elements of the performance has become weird, will be misplaced.

The solution to the problem at the application level 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 events, and detect scroll or resize events, there will be a certain delay, there will be flicker, so the best solution is setinterval Timer monitor the current focus element is a text element, if so, it needs to be processed, This solves the fixed element error problem.

fixed element sliding Inertia smoothing degree

We often encounter this product demand, Tab tab bar Start fixed, when scrolling down over the tab bar will become a fixed element, always appear in the head, such demand on the computer is not a problem, but the iphone5s below the mobile phone often appear small range dislocation or rapid movement of large-scale dislocation problem.

This time we can cause reflow to force the browser to redraw to solve this problem, here is recommended a strange hack writing: At the same time, set the SRC attribute of the three image elements, it can solve the problem all over the world, the scheme is confirmed by the team and applied.

Three pictures src, triggering reflow, dealing with fixed scheme inertia problem

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 below the tab tag has animation, but may not move on the Xiaomi or Samsung phone, this time can also dynamically cause reflow to solve the bug.

Other

The CSS selector uses the ID and class as much as possible to avoid excessive stacking

L Avoid using numeric values, such as: Border:none does not cause rendering, and boder:0

L ANIMATE the elements out of the flow of the document to avoid causing a large number of reflow

L Avoid modifying the DOM style, changing the classname to achieve the same function

L Set Display to none when manipulating the DOM, because this element does not affect rendering, or the manipulation of the Fragment object supersedes the DOM displayed on the page

L Avoid writing operations that get DOM style attributes in loops, which can cause duplicate reflow

Memory Resource OptimizationJavaScript on the mobile side

First of all, the performance of the mobile side and the performance of the PC is not at the same order of magnitude, for example, my brother did a test, using innerHTML to draw a large segment, and then want to get the ID node of the HTML, in fact, is not acquired, this problem in a single page simulation of multiple pages, dynamic creation of DOM will often occur

var element = $ (' <div id = ' Test '; A large number of structural ...</div> ');

$ (root). HTML (Element)

$ (' #test)//Is empty

This kind of problem is unthinkable, because page UI rendering is mutually exclusive with DOM operation, but even if this problem arises, one solution is to use settimeout, and a better solution is to use the Domnoderemoved event to monitor the page DOM changes, Put our DOM action callback to ensure that the rendering is finished.

The above problem is just to illustrate the performance of the mobile side, such performance problems can lead to a lot of inexplicable problems, and many are related to rendering. But this also from the side to explain the shortage of mobile resources, if the heap value is too large, will result in the operation of card phenomenon, what is more, will cause the page suspended animation directly exit.

WebApp mode, completely dependent on the browser's garbage collection, basically is to die, because the traditional page once the page refreshes the entire resource is completely released, and WebApp does not refresh such operations, there is only one State to 21 states, the unrelated memory will be retained, the resource must be released manually, or, The framework must provide a mechanism for garbage release.

This is clearly seen by the changes in the chart heap values.

In the view switching process, the unused resources, if not manually set to NULL, can cause the variable to not be recycled and out of frame control. So we need to pay attention in the process of WebApp:

L Release unused closures

L The Observer needs to be cleaned up.

L Release Timer

• Release view-related resources in destroy during view switching

--Thanks to Allen for his support.

Closure traps

In the course of our work, the abuse of local variables is highly likely to cause closure traps, which is not only a performance problem, but is logically caused by errors and is not easy to find, for example, using a local variable in AMD closures

var _attributes = {};

Callback ($.extend (_attributes, opts));

This will change the _ Attributes object, if an instance is not a problem, but two instances of the variable pollution will occur.

This is only an example, but the misuse of local variables in code can cause unnecessary worries and cautions.

WebApp Resource Release

According to the previous description, we can draw a conclusion:

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

If the view resource is not released causing the heap value to be too high, the value of the WebApp mode site is greatly reduced. Here are a few things to consider:

L WebApp Save no more than 5 view instances, and then release the DOM structure and memory references ( critical value to determine the optimal )

L Free Internal resources when view is hidden, release DOM event handle

The UI component is the same as view and requires a unified release mechanism

However, the single page application because the page does not refresh, there are always some resources are not released, this problem, usually the writing process can do the following optimizations:

L use functions to replace logic

The first benefit of having our function produce a large block of logic in a return value substitution function is a clear logic, and the second benefit is that these functions are automatically freed when used in different functions.

L Cleanup Closure Reference

When a closure function or what is used, if it is no longer used, it is necessary to manually clean up the variable so that the referential relationship between the closures is freed and resources are released.

L Use Object properties or methods

An object can refer to properties or methods of other objects, such as Obj.foo = Thatobj; In this case, we can remove the object dereference at any time, and then we can clean up the resource.

Animations and suspended animation

Animation is recommended to use CSS3 to achieve animation, CSS3 also recommended the latest interface, such as the use of transform instead of top/lelf operation, so that the operation more efficient.

If you use animations to set the corresponding element to absolute to reduce reflux, the most critical point is

Avoid moving the DOM tree too many nodes, this time need to dismiss the product unreasonable demand, such as:

Product Requirements Date scrolling component, showing half-yearly data, this half-year data is 180 dom tree

This level of DOM once moved the entire phone will die directly, or even build a DOM tree, rendering the page will also appear suspended animation phenomenon, the problem needs to be circumvented.

Application Cache

Application cache is an API added to HTML5 for WebApp offline use, unlike Localstorage, cookies, application cache stores a series of request resources that allow the browser to request resources without passing through the network. If designed properly, it can be applied offline.

The use of application cache is mainly to improve network performance, effectively reduce network latency, improve request acceleration

However, there are some problems , such as the new version cache does not take effect immediately, the request path in the manifest is relative to the manifest file, not the loading page, update/rollback and so on, so the use or not is justified.

Experience optimized area scrolling

The mobile side often needs to realize the demand of the area rolling, the mature also has the Iscroll solution, but the solution is not ideal.

In the case of official examples, the following problems arise:

L head disappears.

L Occasionally cannot display text box focus, or focus dislocation

If the above problems can be ignored, but the text box is missing this kind of thing, I will not accept

The cause is related to the organization browser default event, so I don't recommend you to use area scrolling in a wide range,

Just go. The ipad version uses iscroll in a place with a text box, and its improved user experience is as compelling as the problem it causes.

In fact, the message and its respected Iscroll library, although he has such a problem, but,Iscroll is most likely to bring the mobile revolution of the library , because he can:

① Resolving WebApp Area scrolling

② fix fixed problem in disguise

③ solve the problem of short and long pages caused by animation process

All in all, the Iscroll solution is to make webapp comparable to native app close to a big step, real equals also need browser support

Click Response

The click itself in the mobile response is no problem, but we click on the 300ms delay is a fact, the fact that the cause is

Phone needs to know if you want to double-click to enlarge Web content

So click click Response Slow, and touch does not have such a limit, so the mobile side of the touch is quite popular, as for the mouse slow, how slow he is, I will tell you each time will be slow 300ms

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

Conclusion

WebApp is not a day two days of things, one day, WebApp will bloom its due style!

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.