search
HomeWeb Front-endJS TutorialHow 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

How to achieve high-performance mobile development


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

How to achieve high-performance mobile development

#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.

How to achieve high-performance mobile development

#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 :

How to achieve high-performance mobile development

#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

elements with 3D (WebGL) context or accelerated 2D context

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

How to achieve high-performance mobile development

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.

How to achieve high-performance mobile development


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.

How to achieve high-performance mobile development


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

How to achieve high-performance mobile development

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');
}


2. Closure cache calculation results (functions that require frequent calls and calculations)

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


3. Debounce the user input event processing function

If The touched element is bound to the input

event processing function, such as touchstart/touchmove/touchend, then the rendering layer merging thread must wait for the completion of the execution of these bound processing functions before it can be executed, that is, the user's scrolling page The operation is blocked, and the behavior is that the scrolling is delayed or stuck.

In short, you must ensure that any processing function bound to the user input event can be executed quickly to free up time for the rendering layer merger thread to complete its work.

Input event processing functions, such as scroll/touch event processing, will be called and executed before requestAnimationFrame. Therefore, if you modify the style attributes in the above input event handler, these operations will be temporarily stored by the browser.

Then when calling requestAnimationFrame, if you read the style attributes at the beginning, it will trigger the browser's forced synchronization layout operation (ie, perform layout in the javascript stage), so This will lead to multiple layouts and low efficiency.

Optimization is as follows:

window.requestAnimationFrame(function () {
    context.animateTo(nowPos);  //需要更新位置的交给RAF
});


4. Reduce unnecessary redrawing

Continuing from the above, after turning on paint flashing, you can see Which areas the browser repaints. I found that some unnecessary redrawing areas were also redrawn~ Enable GPU optimization for these (mentioned above)

Look at the timeline effect directly, it is all green~I finally let go of my hanging heart

How to achieve high-performance mobile development

How to achieve high-performance mobile development

There are many tips for mobile development. Today I will bring you this high-performance development tip. More For knowledge, please continue to pay attention to our website PHP.cn

Related reading:

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.