preface

The book I recommend for this week is High Performance JavaScript, where you can learn about performance bottlenecks in JavaScript development and how to improve performance in all aspects of code loading, running, DOM interaction, page life, and more. Again, we’re going to do a close reading today using mind maps. (Mind map images may be a little small, but click on them and you’ll learn something.)

Load and execute

Managing JavaScript code in a browser is a tricky problem because code execution blocks other browser processes, such as user interface drawing. Every time meet<script>Tag, the page must stop and wait for code to download (if external) and execute before proceeding to the rest of the page. However, there are several ways to reduce the impact of JavaScript on performance:

  1. Will all<script>The tag is placed at the bottom of the page, close next to the body tag</body>On the top. This ensures that the page is parsed before the script runs.
  2. Package scripts as groups. Of the page<script>The fewer tags, the faster the page loads and the more responsive it is. This is true of external script files as well as inline code.

There are several ways to download JavaScript using non-blocking methods:

  • for<script>Tag Add the defer attribute (Only available in Internet Explorer and Firefox 3.5 and up)
  • Dynamically create<script>Element with which to download and execute code
  • Download the code with the XHR object and inject it into the page

By using these strategies, you can greatly improve the actual performance of web applications that use a lot of JavaScript code.

Data access

In JavaScript, the location of data storage can have a significant impact on the overall performance of your code. There are four types of data access: direct, variable, array items, and object members. They have different performance considerations.

Direct and local variable access is very fast, and array items and object members take longer. A local variable is faster than an out-of-domain variable because it is in the first object in the scope chain. The deeper a variable is in the scope chain, the longer it takes to access it. Global variables are always the slowest because they are always at the end of the scope chain. Avoid using the with expression because it alters the scope chain of the runtime context. You should also be careful with the catch clause of a try-catch expression, because it has the same effect. Nesting object members can have a significant performance impact; use them sparingly.

The deeper a property or method is in the primitive chain, the slower it is to access it. In general, you can improve the performance of your JavaScript code by storing frequently used object members, array items, and out-of-domain variables in local variables. Local variables can then be accessed faster than the original ones. By using these strategies, you can greatly improve the actual performance of web applications that require a lot of JavaScript code.

DOM programming

DOM access and manipulation is an important part of modern web applications. But every time you cross the bridge from ECMAScript island to DOM island, you will be charged a “bridge toll”. To minimize the performance penalty in DOM programming, keep the following in mind:

Minimize DOM access and do as much as you can on the JavaScript side. Use local variables to store DOM references where they are accessed repeatedly. Handle HTML collections with care because they show “presence” and always re-query the underlying document. The length attribute of the collection is cached into a variable that is used during iteration. If you manipulate the collection often, you can copy the collection into an array.

If possible, use faster apis such as querySelectorAll() and firstElementChild. Pay attention to redrawing and retypesetting; Modify styles in batches, manipulate DOM trees offline, cache and reduce access to layout information. Use absolute coordinates in animations, using drag and drop agents. Minimize the number of event handles using event hosting techniques.

Algorithm and process control

As with other programming languages, the way the code is written and the algorithm chosen affects the runtime of JavaScript. Unlike other programming languages, JavaScript has limited resources available, so optimization techniques are even more important.

For,while, and do-while loops have similar performance characteristics; none is faster or slower than the other. Do not use for-in loops unless you are iterating over an object with unknown attributes. The best way to improve loop performance is to reduce the amount of computation in each iteration and to reduce the number of iterations of the loop.

In general,switch is always faster than if-else, but not always the best solution. Table lookup is faster than if-else or switch when there are many criteria.

The size of the browser call stack limits the application of recursive algorithms in JavaScript. Stack overflow errors cause other code to fail as well. If you encounter a stack overflow error, change the method to an iterative algorithm or use tabulation to avoid rework.

The greater the total amount of code running, the greater the performance gain from using these policies.

Strings and regular expressions

Intensive string manipulation and shallow writing of regular expressions can be major performance hurdles, but the recommendations in this chapter can help you avoid common pitfalls. Array union is the only method on IE7 and its earlier versions that has reasonable performance when concatenating large numbers or sizes of strings. If you don’t care about IE7 and its earlier versions, array union is one of the slowest ways to concatenate strings. Use simple + and += instead to avoid unnecessary intermediate strings.

Backtracking is not only a basic part of regular expression matching, but also a common reason why regular expressions affect efficiency. Backtracking occurs where the regular expression should find a match quickly because of some particular action to match the string, causing it to slow down or even crash the browser. Techniques to avoid this problem include making adjacent characters mutually exclusive, avoiding nested quantifiers matching the same part of a string more than once, and removing unnecessary backtracking by reusing the atomic nature of forward-looking operations.

Various techniques to improve regular expression efficiency help regular expressions find matches faster and spend less time on non-match locations (see More ways to Improve Regular expression efficiency). Regular expressions aren’t always the best tool to get the job done, especially if you’re just searching for a text string.

While there are many ways to trim a string, using two simple regular expressions (one to remove header whitespace and one to remove tail whitespace) provides a concise, cross-browser approach to strings of varying content and length. Looping to find the first non-space character from the end of the string, or in a hybrid application combining this technique with regular expressions, provides a good alternative that is less affected by the overall length of the string.

Quick response user interface

JavaScript and user interface updates run in the same process, and only one of them can be running at a time. This means that the user interface cannot respond to input while the JavaScript code is running and vice versa. Managing UI threads effectively is all about making sure that JavaScript doesn’t run for too long without affecting the user experience. Finally, keep the following points in mind:

  1. JavaScript should not run for more than 100 milliseconds. Long runtimes lead to appreciable delays in UI updates, which negatively impact the overall user experience.
  2. Browsers differ in how they respond to user interactions while JavaScript is running. However,JavaScript running for long periods of time can lead to a confusing and disjointed user experience.
  3. Timers can be used to schedule deferred code execution and allow you to break long running scripts into a series of smaller tasks.

Web worker threads are a feature supported by modern browsers that allows you to run JavaScript code outside of the UI thread without locking the UI. The more complex a Web application becomes, the more important it becomes to proactively manage UI threads. No JavaScript code is important enough to affect the user experience.

Ajax

High-performance Ajax involves knowing the specific requirements of your project and choosing the right data format and transfer technology to match it.

As data formats, plain text and HTML are highly limited, but they save the client CPU cycles. XML is widely used and universally supported, but it is very verbose and slow to parse. JSON is lightweight, parses quickly (as native code rather than strings), and is comparable to XML in interoperability. The custom format of character separation is very lightweight and fastest when parsing large data sets, but requires writing additional programs to construct the format on the server side and parse it on the client side.

XHR provides the most complete control and flexibility when requesting data from a page domain, although it treats all incoming data as a string, which can slow parsing. Dynamic script tag insertion, on the other hand, allows cross-domain requests and native running of JavaScript and JSON, although its interface is not secure enough to read headers or response message codes. Multipart XHR reduces the number of requests and can process different file types in a single response, although it cannot cache received response packets. Image lights are the simplest and most efficient way to send data. XHR can also send large amounts of data using the POST method.

In addition to these formats and transport technologies, there are a few guidelines that can help speed up Ajax even further:

  1. Reduce the number of requests by packing JavaScript and CSS files, or by using MXHR.
  2. Shorten page load time by using Ajax to fetch a few important files after the rest of the page has loaded.
  3. Ensure that code errors are not displayed directly to the user and that errors are handled on the server side.
  4. Learn when to use a robust Ajax library and when to write your own low-level Ajax code.

Ajax is one of the biggest areas of improvement for your site’s potential performance, both because many sites make heavy use of asynchronous requests and because it provides a solution to many unrelated problems, such as loading too many resources. The creative use of XHR is so different that it is not a dull and unfriendly interface, but a byword for responsiveness and efficiency; It won’t be hated by users. Everyone will love it when they see it.

Programming practice

JavaScript presents some unique performance challenges related to the way you organize your code. As web apps become more sophisticated, with more JavaScript code, patterns and anti-patterns emerge. Keep the following programming lessons in mind:

  1. Avoid secondary evaluation by avoiding the use of eval_r() and Function() constructors. In addition, setTimeout() and setInterval() are passed function arguments instead of string arguments.
  2. New objects and arrays are created using object and array quantities. They are faster to create and initialize than indirect quantitative forms.
  3. Avoid doing the same thing twice. Use lazy loading or conditional preloading when you need to detect the browser.
  4. When performing mathematical telematics, consider using bitwise operations, which operate directly at the bottom of the number.
  5. Native methods are always faster than JavaScript writing. Use native methods whenever possible.

Build and deploy high-performance javascript applications

The development and deployment process can have a huge impact on javascript-based applications, and the most important steps are as follows:

  1. Merge JavaScript files to reduce the number of HTTP requests
  2. Use the YUI compressor to compact JavaScript files
  3. Provide JavaScript files in compressed form (gZIP encoded)
  4. Make JavaScript files cacheable by setting HTTP response headers and solve caching problems by attaching time stamps to file names
  5. Provide JavaScript files using a Content Delivery Network (CDN), which not only improves performance, but also manages compression and caching for you

All of these steps should be done automatically, either using a public development tool such as Apache Ant or using custom development tools to implement specific requirements. If you make these development tools work for you, you can greatly improve the performance of web applications or websites that use a lot of JavaScript code.

tool

When a web page or application is slow, analyze the resources coming from the web and analyze the performance of your scripts so that you can focus on the areas that need to be optimized. Use a network analyzer to identify bottlenecks in loading scripts and other page resources, which can help determine which scripts need lazy loading or for further analysis. Conventional wisdom tells us to minimize the number of HTTP requests and delay loading scripts to make pages render faster and provide a better overall experience for the user. Use a performance analyzer to find the parts of the script that are slow to run, examine how long each function takes and how many times the function is called, and use clues from the call stack itself to figure out where to optimize. Although the time spent and the number of calls are usually the most valuable points in the data, you should look closely at how a function is called, and you may find ways to optimize it. These tools are no longer a mystery in the programming environment in which modern code runs. Use them before you start tuning to make sure the development time is on the right side of the problem.

😊 Previous reading notes && technical articles

In order to connect the front-end knowledge of the system, I like to use mind maps to record reading notes. I built a warehouse on Github to store the original mind maps and reading notes. If you also like to use mind map to record reading notes, you are welcome to maintain this warehouse with me. Please leave a message or communicate with me on wechat (646321933)

Close Reading of javascript You Don’t Know (Volume 1)

Close reading volume 2 of javascript You Don’t Know

Intensive reading of Node.js

Close reading of Illustrated HTTP

Javascript garbage collection algorithm

What you need to know about single-page routing

Javascript implementation of high imitation growingIO

Fresh baked before the End of August test questions

Mind map download address