Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the performance optimization skills of JavaScript?

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "JavaScript performance optimization skills", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what are the JavaScript performance optimization skills" this article.

What is high-performance JavaScript code?

Although there is no absolute definition of high-performance code, there is a user-centric performance model that can be used as a reference: the RAIL model.

Response

If your application can respond to a user's action within 100 milliseconds, the user will consider the response to be immediate. This applies to clickable elements, not scrolling or dragging operations.

Animation

On the 60Hz monitor, we want to animate and scroll at 60 frames per second, in which case each frame is about 16ms. During this 16ms time, there is actually only 8-10ms to do all the work, and the rest of the time is occupied by browser internal and other differences.

Idle work

If you have a task that takes a long time and needs to run continuously, be sure to divide it into small blocks to allow the main thread to react to the user's input. There should not be a user input with a task delay longer than 50ms.

Load

Page loading should be completed within 1000 milliseconds. On mobile devices, this is a difficult goal to achieve because it involves page interaction, not just rendering and scrolling on the screen.

Modern loading best practices (Chrome Dev Summit 2017)

If the loading time of the mobile website is more than three seconds, 53% of the users will give up access.

50% of users want to finish loading the page in less than 2 seconds

77% of mobile websites need more than 10 seconds to load 3G network.

19 seconds is the average loading time of mobile sites on 3G networks.

Code content

As you may have noticed, the biggest bottleneck is the time it takes to load the site. Specifically, it is the download, parsing, compilation, and execution time of JavaScript. There seems to be no other way than to load fewer JavaScript files or load more flexibly.

How does JavaScript code actually work other than launching a website?

Before you optimize your code, consider what you are currently building. Are you building a framework or a VDOM library? Does your code need to perform thousands of operations per second? Are you building a time-sensitive library to handle user input and / or animation? If not, you need to shift your time and energy to a more influential place.

Writing high-performance code is not that important because it usually has no impact on macro planning. 50k ops/s sounds better than 1k ops/s, but in most cases the overall time does not change.

Parsing, compiling, and executing

Fundamentally, the performance problem with most JavaScript is not the running code itself, but the series of steps that must be taken before the code begins execution.

We are talking about the level of abstraction here. Most of the code running on the computer is in compiled binary format. This means that, with the exception of all operating system-level abstractions, the code can be run locally on the hardware without preparation.

The JavaScript code is not precompiled, it is readable on the browser.

The JavaScript code is first parsed, that is, read and converted into a structure of computer indexes that can be compiled, then compiled into bytecode, and finally compiled into machine code for device / browser execution.

Another very important aspect is that JavaScript is single-threaded and runs on the browser's main thread. This means that only one process can be run at a time. If your DevTools performance timeline is full of yellow peaks and the CPU occupancy rate reaches 100%, frames will be lost. This is a common and annoying situation in scrolling operations.

All of this parsing, compilation, and execution needs to be done before the JavaScript code can run. In the ChromeV8 engine, parsing and compilation account for about 50% of the total JavaScript execution time.

So in this section, you should know two things:

1. Although the length of time for JavaScript parsing and the size of the package are not completely linear, the less JavaScript you need to process, the less time it takes.

two。 Every JavaScript framework you use (React,Vue,Angular,Preact...) is another level of abstraction (unless it is a precompiled one). This not only increases the size of your package, but also slows your code because you don't communicate directly with the browser.

Some methods can alleviate this situation, such as using service workers to perform partial work in another thread in the background, or using asm.js to write code that makes it easier to compile machine instructions.

All we can do is avoid using the JavaScript animation library. Use these libraries only if regular CSS transformations and animations are completely impossible.

Even though these JavaScript animation libraries use CSS transformations, composite properties, and requestAnimationFrame (), they still run on the main thread of JavaScript. Basically, these libraries use inline styles to access DOM per 16ms. You need to make sure that all the JavaScript is done within each frame of 8ms in order to keep the animation smooth.

On the other hand, CSS animations and transformations run in the main thread, and relayout / rearrangement can be avoided if it can be performed efficiently.

Considering that most animations are run during loading or user interaction, this can provide a very important tuning space for your web application.

Web Animations API is an upcoming feature set that can perform high-performance JavaScript animations away from the main thread. For now, however, you need to continue to use technologies such as CSS transformations.

Bundling size is very important.

This is no longer an era in which multiple tags are included before closing tags. A variety of toolkits can now be found on npm, and these kits and Webpack can be bundled in a single 1MB-sized JavaScript file to remind the user's browser to crawl when the data plan is completed.

This allows you to use less JavaScript, which means that your project may no longer need the entire Lodash library. If you have to use the JavaScript library, you can also consider using something other than React, such as Preact or HyperHTML, which is only the size of 1 / 20 of React.

Webpack 3 has magical features called code segmentation and dynamic import. Instead of bundling all JavaScript modules into a single app.js package, it automatically splits the code and loads asynchronously using the import () syntax.

You don't need to use frameworks, components, and client routing to get these benefits. You simply write the following in the main JavaScript file:

If (document.querySelector ('.mega-widget')) {import ('. / mega-widget');}

If your application needs to use this widget on the page, it will dynamically load the required support code.

In addition, Webpack needs run time to work and inject it into all the .js files it generates. If you use the commonChunks plug-in, you can extract the runtime into Chunk using the following:

New webpack.optimize.CommonsChunkPlugin ({name: 'runtime',})

Make sure that the Webpack has finished loading before the main JavaScript package, then the elapsed time in all other chunk will be split into their own files, which is also called runtime.js. For example:

Then there is the part of compiling the code and polyfills. If you are writing modern JavaScript code (ES6 +), you can use Babel to convert it to ES5 compatible code. Compared with native ES6+ code, compilation not only increases file size, but also increases complexity, and performance degradation often occurs.

In addition, you are likely to use babel-polyfill packages and whatwg-fetch to fix missing features in older browsers. So if you are writing async/await, you also need to use the package regenerator-runtime generator to compile.

The problem is that you add nearly 100KB content to the JavaScript package, which is not only a huge file, but also foreshadows huge parsing and execution costs to be able to support older browsers.

One way is to create two separate bundle and load them according to the actual conditions. The Babel conversion compiler, with the help of babel-preset-env, will make it easier to deal with both new and old browsers.

A non-standard but effective approach is to put the following in an inline script:

(function () {try {new Function ('async () = > {}') ();} catch (error) {/ / create script tag pointing to legacy-bundle.js; return;} / / create script tag pointing to modern-bundle.js;;}) ()

If the browser does not recognize the async function, it is considered an older version of the browser, and the polyfill package is used. If it can be identified, the user will be handled by a modern browser.

The above is all the content of the article "what are the JavaScript performance optimization techniques?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report