How to achieve high-performance mobile development
As we all know, the mobile terminal should not only load quickly, but also have content without user experience. It should also run smoothly, such as quick-response interactions and silky-smooth animations...
How to achieve the above effects in actual development?
1. Confirm the analysis standards of rendering performance
2. Prepare a ruler to measure the rendering performance standards
3. Optimize the most time-consuming areas
We can roughly get the following optimization goals
The first one is the first screen presentation time. The online information has There are many, many, compressed codes, use webp images, use sprites, on-demand loading, "direct out", CDN...
The second one is 16ms optimization. This article focuses on 16ms optimization.
1. Browser renderingPrinciple introduction
The refresh frequency of most devices is 60 times/second, (1000/60 = 16.6ms) In other words, the browser's rendering of each frame must be completed within 16ms. Beyond this time, the rendering of the page will be stuck, affecting the user experience.
This is what is shown in the above picture
#If the attribute is changed further to the left in the above picture, the greater the impact and the lower the efficiency. .
The browser rendering process is as follows:
Get the DOM and split it into multiple layers (RenderLayer)
Rasterize each layer and draw it independently In the bitmap,
upload these bitmaps to the GPU as textures
Composite multiple layers to generate the final screen image (ultimate layer).
As can be seen from the above figure, if you just change the composite (merging of rendering layers), the efficiency will be greatly improved.
The following is a rough list of which styles will change which module of the rendering process.
#As you can see from the picture above, transform and opacity will only change composite (rendering layer merging). Why? Because GPU acceleration is turned on.
Turn on GPU acceleration
Literal explanation: Textures can be mapped to different locations at a very low cost, and they can also be applied to a very simple Transform into a rectangular grid.
[The literal understanding is very convoluted, but it is still the same old truth. Don’t use words if you can explain it clearly with pictures. 】
Small tips: First select a frame of the timeline, then select the layer label tab below, you can drag the module left and right to appear 3d
We can see that the page is composed of the following layers :
#Although what we end up seeing on the browser is just a copy, that is, there is only one layer in the end. Similar to the "layer" concept in PhotoShop software, all available view layers are finally merged and a picture is output to the screen
But in fact a page will Because some rules are divided into corresponding layers, once they are independent, they will not affect the layout of other DOM, because after it is changed, it is only "pasted" to the page.
Currently the following factors will cause Chrome to create layers:
3D or perspective transform (perspective transform) CSS properties
Use the
Mixing plug-ins (such as Flash)
Do CSS animations on their own opacity or use an animation webkit-transformed elements
Elements with accelerated CSS filters
Elements have a descendant node that contains a composite layer (in other words, an element has a child element , the child element is in its own layer)
The element has a sibling element with a lower z-index and contains a composite layer (in other words, the element is rendered on top of the composite layer)
In webkit-based browsers, if the above situation occurs, an independent layer will be created.
Be careful not to create too many rendering layers, which means new memory allocation and more complex layer management. Don't abuse GPU acceleration, pay attention to whether composite layouts exceed 16ms
Having said so many principles of browser rendering, it is useless to measure without a ruler. So, let’s choose a ruler to measure: Timeline of Google development tools.
2. Common functions of Google development tool Timeline
1. After clicking Record in the upper left corner, the recording ends The following will be generated. The red area is the frame. Move up and you can see the frequency of each frame. If it is >60fps, it is relatively smooth.
2. Under the timeline, you can see the time-consuming of each module, and you can locate the time-consuming ones. Above the function, optimize the function.
3. Follow the steps below to select and you can see the independent layer and highlight the redrawn area, which is convenient Find the unnecessary redrawing areas and optimize them
After selection, the following 2 color borders will appear on the current page
Yellow border: Elements with animated 3D transformations are placed in a new composite layer (composited layer) to render
Blue grid: These blocks can be regarded as lower-level units than the layer, Chrome Taking these chunks as units, the content of one chunk is uploaded to the GPU at a time.
The tools are also available, and the principles of browser rendering are also known. The next step is to optimize based on actual projects.
3. Conduct in actual projects 16.6ms optimization
Combined with the above rendering flow chart, we can analyze and optimize the following steps
OptimizationJavaScriptexecution efficiency
Reduce the scope and complexity of style calculation
Avoid large-scale, complex layouts
Simplify the complexity of drawing and reduce the drawing area
Prioritize the use of rendering layer merging attributes, Number of control layers
Debounce processing function for user input events (mobile devices)
1. Separation of reading and writing, batch operations
## When the #JavaScript script is running, the element style attribute values it can obtain are all from the previous frame, and they are all old values. Therefore, if you make changes to the element node before obtaining the attributes in the current frame, it will cause the browser to first apply the attribute modifications, then execute the layout process, and finally execute the JavaScript logic.// 先写后读,触发强制布局 function logBoxHeight() { // 更新box样式 box.classList.add('super-big'); // 为了返回box的offersetHeight值 // 浏览器必须先应用属性修改,接着执行布局过程 console.log(box.offsetHeight); }After optimization:
// 先读后写,避免强制布局 function logBoxHeight() { // 获取box.offsetHeight console.log(box.offsetHeight); // 更新box样式 box.classList.add('super-big'); }
getMaxWidth: (function () { var cache = {}; function getwidth() { if (maxWidth in cache) { return cache[maxWidth]; } var target = this.node, width = this.width, screen = document.body.clientWidth, num = target.length, maxWidth = num * width + 10 * num + 20 - screen; cache[maxWidth] = maxWidth; return maxWidth; } return getwidth; })(),After changing to this method, it just works~ It reduces more than 10 ms
window.requestAnimationFrame(function () { context.animateTo(nowPos); //需要更新位置的交给RAF });
Mobile terminal development: Handling the horizontal and vertical screens of mobile devices
Essential knowledge for mobile terminal development (reprint)_html/css_WEB-ITnose
Some tips for mobile development_html/css_WEB-ITnose
The above is the detailed content of How to achieve high-performance mobile development. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
