JavaScript Performance Optimization tips sharing

Source: Internet
Author: User
Tags script tag cpu usage http 2

JavaScript, as the most common literal-translation scripting language, has been widely used in WEB application development. In order to improve the performance of Web applications, it is a good choice to start with the JavaScript performance optimization direction.

This article explains JavaScript's performance optimization techniques from loading, context, parsing, compiling, executing, and bundling, so that more front-end developers can master this knowledge.

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: rail model.

    • Response

If your application responds to a user's actions within 100 milliseconds, the user considers the response to be instantaneous. This applies to clickable elements and does not apply to scrolling or dragging operations.

    • Animation

On a 60Hz monitor, we want to animate and scroll with 60 frames per second, in this case approximately 16ms per frame. In this 16ms time, actually only 8-10ms to do all the work, the rest of the time by the browser's internal and other differences occupy.

    • Idle work

If you have a task that takes a long time to run, be sure to break it down into small chunks that allow the main thread to react to the user's input operations. There should be no more than 50ms user input for a task delay.

    • Load

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

Modern loading best Practices (Chrome Dev Summit 2017)

Let's take a look at some stats:

    • If the mobile site is loaded for more than three seconds, then 53% of the users will give up access
    • 50% of users want to complete the page load in less than 2 seconds
    • 77% of mobile sites require more than 10 seconds to load 3G networks
    • 19 seconds is the average load time of a mobile site on a 3G network

Code Content

As you may have noticed, the biggest bottleneck is the time it takes to load the site. Specifically, JavaScript downloads, parses, compiles, and executes the time. In addition to loading fewer JavaScript files or loading more flexibly, there seems to be no other way.

How does the JavaScript code actually work except the startup site?

Before you do code optimization, consider what you are currently building. Are you building a framework or a vdom library? Does your code need to perform operations thousands of times per second? Are you working on a library that is more time-critical to handle user input and/or animations? If not, you need to shift your time and energy to a more influential place.

Writing high-performance code is not so important because it usually has little impact on macro plans. 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 of most JavaScript does not lie in running the code itself, but in a series of steps that must be taken before the code starts to execute.

We are here to discuss the question of abstraction level. Most of the code that runs on the computer is the compiled binary format. Meaning, except for all the operating systems?? System-level abstraction, code can be run locally on hardware without the need to prepare for work.

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

The JavaScript code is parsed first, that is, the structure that reads and transforms the index of the computer that can be compiled, and then is compiled into bytecode, which is then compiled into machine code for device/browser execution.

Another very important aspect is that JavaScript is single-threaded and runs on the main thread of the browser. This means that only one process can run at a time. If your DevTools performance timeline is full of yellow peaks and the CPU usage reaches 100%, the drop frame will occur. This is a common occurrence of rolling operations, but also a very annoying situation.

All of this parsing, compiling, and executing work needs to be done before the JavaScript code runs. In the ChromeV8 engine, parsing and compiling accounted 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 is spent.

2. Every JavaScript frame you use (react,vue,angular,preact ... ) is another level of abstraction (unless it is a precompiled one). This will not only increase the size of your package, but will make your code slower because you are not directly communicating with the browser.

There are ways to mitigate this, such as using service workers to perform some 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 you are completely unable to implement them using regular CSS transformations and animations.

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

CSS animations and transformations, on the other hand, run in the main thread and can avoid re-layout/rearrangement if executed efficiently.

Given that most animations run during load or user interaction, this can provide a very important space for your Web application to adjust.

The Web animations API is an upcoming feature set that can perform high-performance JavaScript animations out of the main thread. But for now, there is a need to continue using techniques such as CSS transformations.

bundle size is very important

It is no longer the time to include multiple <script> before the </body> end tag. Now, you can find a variety of toolkits on NPM, and you can bundle these toolkits and Webpack in a single 1MB-size JavaScript file that reminds the user of the browser to crawl when the data plan is completed.

This makes it possible to use a smaller amount of JavaScript, which also means that your project may no longer need the entire Lodash library. If you have to use JavaScript libraries, you can also consider using things other than React, such as Preact or hyperhtml, which are just the size of the React 1/20.

Webpack 3 has magical features called code splitting and dynamic import. Instead of bundling all JavaScript modules into a single app.js package, it uses the import () syntax to automatically split the code and asynchronously load it.

You don't need to use frameworks, components, and client-side routing to get these benefits. You simply need to 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 to run the time to work and inject it into all the. js files it generates. If you use the Commonchunks plug-in, you can use the following to extract the runtime into Chunk:

New Webpack.optimize.CommonsChunkPlugin ({  ' runtime ',}),

Make sure that Webpack is loaded before the main JavaScript package, and that the runtime in all other chunk is stripped into its own file, which is also a runtime.js. For example:

<script src= "Runtime.js" ><script src= "Main-bundle.js" >

Then there is the compilation code and the Polyfills section. If you are writing modern JavaScript code (ES6 +), you can use Babel to convert it to ES5-compatible code. Compared to native es6+ code, compilation increases the size of the file, adds complexity, and often degrades performance.

In addition, you are likely to use the Babel-polyfill package and Whatwg-fetch to fix missing features in older versions of the browser. So if you are writing async/await, you also need to use the generator of the package regenerator-runtime to compile.

The problem is that you've added nearly 100KB of content to the JavaScript package, which is not only a huge file, but also a huge parsing and execution cost to support the older versions of the browser.

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

An not-so-canonical but effective method 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 will be considered an older version of the browser, and the Polyfill package will be used. If it can be identified, the user will be treated with a modern browser.

Conclusion

To improve the speed of your website, you need to ensure that your Web site can quickly load JavaScript files for quick interaction. Your JavaScript code should be split into smaller, manageable bundles, and asynchronously loaded as much as possible. On the server side, make sure that HTTP 2.0 is enabled for faster parallel transfers and Gzip/brotli compression, which greatly reduces the size of the JavaScript transfer.

Original link: https://www.sitepoint.com/javascript-performance-optimization-tips-an-overview/

Reproduced please specify from: Grape City control

Related reading:

Shorthand tips for JavaScript developers to know

1 minutes to choose the most appropriate JavaScript frame for you

Top ten JavaScript Editor, which do you use?

JavaScript Performance Optimization tips sharing

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.