defects

The book was published in 2010, the book talk about performance is timeliness, now 2018, front-end development speed is very fast in recent years, some content considered in the book 6, 7, 8, but these are no longer considered now, so inevitably there are some knowledge is older. Some solutions are no longer the best solution, such as the tools chapter.

preface

In general, the performance optimization suggestions given in this book as a whole and the author’s patient practice are very enlightening and helpful for us to develop optimization, because a lot of knowledge in this book is summed up by the author through practice, which is the accumulation of experience, which cannot be learned in ordinary textbooks. Especially for js foundation is a little less, there are a lot of knowledge points although it is still very necessary.

Below I will each chapter of some important knowledge points summary to write out, for dry goods are extracted.

This post was originally posted on my blog:obkoro1.com


The body of the

Chapter 1 – Loading and Execution

  1. Blocking features of js:

When the browser executes JS code, it cannot do other things at the same time. (The UI thread and the JS thread use the same process, so the longer the JS execution, the longer the response time of the page.)

  1. Location of script

If the script

Performance improvement: It is recommended that all

  1. Component scripts.

Each

Merging external linked JS files: HTTP requests incur additional performance overhead: downloading one 100KB JS file is faster than downloading four 25KB JS files. Search for specific operation methods.

  1. Methods for non-blocking scripts

The ayNC property of the script tag:

The async property specifies that scripts are executed asynchronously once they are available. The async property only works with external scripts (only if the SRC property is used). If async=”async” : the script executes asynchronously relative to the rest of the page (the script will be executed while the page continues parsing)

The defer attribute of the script tag:

The js file is downloaded when the page is parsed to the script tag, but is not executed. The DOM load completes execution. The difference between these two attributes is execution timing.

Dynamic script elements.

Js operates dom to create

3. XHR Ajax script injection

Request a file with GET, and that’s it. Then create the dynamic script and add it. Defect: the file is requested in the same domain as the page. Cannot be downloaded from CDN

Chapter 1 Summary of Loading and Execution:

  1. Sign the document with the body tag,
  2. Merge scripts, reduce<script>The label.
  3. Download JS without blocking. Use script’s defer and async properties to download asynchronously. Dynamically create script tags and execute code.

Chapter 2 – Data access

  1. Js four basic data access locations. 1. Literals: string, number, Boolean, object, array, function, re, NULL, undefined. Literals only represent themselves and have no storage location. 2. Local variables. Let var Specifies the declared variable. 3. Array elements. Object members.

Performance: Literals and local variables are the fastest to access, arrays and object members are relatively slow

  1. Variable identifier parsing process:

Search the scope chain of the execution environment for identifiers of the same name. The search process starts at the head of the scope chain, the active object of the currently running function. If found, use this identifier, corresponding variable; If not, continue searching for the object below. The search continues until an identifier is found. If no match is found, the identifier is considered undefined,

Performance issues: The deeper an identifier is, the slower it reads and writes. Therefore, reading and writing local variables in a function is always the fastest, while reading and writing global variables is usually the slowest.

Suggestion: Save global variables to local variables to speed up reading and writing.

  1. Closures, prototypes, nested objects.

Optimization tip: Store commonly used cross-scoped variables into local variables and then access local variables directly. The reason above is that variable identifiers are resolved during the process.

Chapter II Summary of Data Access

  1. Literals and local variables are the fastest to access, whereas array elements and object members are relatively slow to access.
  2. Because local variables exist at the start of the scope chain, it is faster to access local variables than cross-scope variables. The same goes for arrays, objects, and cross-scoped variables.
  3. Storing commonly used objects, arrays, and cross-domain variables in local variables can improve JS performance and speed up local variable access.

Chapter 3 DOM Programming Summary:

  1. Dom manipulation is inherently slow, so minimize dom manipulation and dom access.
  2. Using Document. querySelect to make a selector is faster than other methods.
  3. You need to access a DOM node multiple times, using local variable storage.
  4. HTML collection, cache the length of the collection into a variable, and then iterate through the use of this variable, if you often operate on the collection, it is recommended to copy to an array.
  5. Keep an eye out for browser redraws and rearrangements; When changing styles in batches, manipulate the DOM tree ‘offline,’ use caching, and reduce the number of times you have to access layout information. Redraw and rearrange is a fairly important concept in DOM programming optimization: redraw and rearrange.
  6. Use absolute definitions in animations, using drag and drop.
  7. Use event delegates to reduce the number of event handlers.

Chapter 4 Algorithm and Process Control Summary:

  1. For, while, and do-while loops perform similarly, with for-in loops only one-seventh the speed of the previous types, so avoid for-in loops unless you need to iterate over an object with an unknown number of attributes.

    ForEach is slower than for. Do not use forEach if the running speed is strict.

  2. The best way to improve loop performance is to reduce the amount of work per iteration and reduce the number of loop iterations.

Reduce iteration effort: reduce attribute lookup and reverse loop, the more loops, the more obvious the performance optimization.

for(var i=0; i<items.length; Var I =items.length; var I =items.length; I --){code}// reverse loop // reduce attribute lookup: find a property once, store the value in a local variable, use this variable reverse loop in the control condition automatically converts to true if I >0, false if I = 0. // Reverse loop: Control conditions from (is the number of iterations less than the total? Is it true? Becomes (is it true)Copy the code

Reduce the number of iterations: the “Duff’s Device” loop body unwinding technique, for those interested, is suitable for iterations greater than 1000.

  1. If-else vs. switch: The larger the number of conditions, the more likely it is to use switch.

    To optimize the if – else:

    1. Prioritize the most likely scenario. 2. Divide the range of values into a series of intervals using dichotomy.Copy the code
  2. The size of browser call stack limits the application of recursive algorithm in JS. Stack overflow errors cause other code to stop running.

    Use recursion with care, now es6 recursion can be tail-recursion, in ES6 as long as the use of tail-recursion does not occur stack overflow, relative performance savings.Copy the code

Chapter 5: Strings and Regular Expressions

  1. String merges use simple ‘+’ and ‘+=’ operators.

    str+='abc'+'efg; // More than 2 string concatenation will produce temporary string STR = STR +' ABC '+'efg'; // Speed up by 10%~40% is recommendedCopy the code
  2. It’s important to find a blog post about the principles of regex and backtracking in the book: it’s pretty much the same as the book, but I encourage you to check out the regular expressions section in the PDF.

  3. Methods to improve the efficiency of regular expressions:

    1. Most importantly: Externalize regular expressions! Externalize regular expressions! Externalize regular expressions! 2. Focus on making matches fail faster, and find the required, special characters. 3. 4. Use quantifier patterns so that the characters after them are mutually exclusive. Use appropriate quantifiers. Assign regular expressions to variables and reuse them. Break complex regex into simple fragmentsCopy the code
  4. Regular expressions aren’t always the best solution when you’re just searching literal strings or when you know in advance what part of the string will be searched:

    Using indexOf() and lastIndexOf() is better for finding the position of a particular string or determining whether they exist // e.g., the current browser.Copy the code

Chapter 6 Quick Responsive USER Interface Summary:

Js and UI updates run in the same process, so only one thing can be done at a time. Managing UI threads efficiently is all about making sure that JS doesn’t run for too long to affect the user experience.

  1. Browsers limit the running time of JS tasks, which is necessary to ensure that some malicious code cannot lock the user’s browser with intensive operations that never stop. This limitation falls into two categories: the size of the call stack and long-running scripts.

  2. No JS task should execute for more than 100 milliseconds. Long runtimes can lead to significant delays in UI updates, which can negatively impact the user experience.

  3. Timers are used to schedule delayed code execution and allow you to break long-running scripts into a series of smaller tasks.

Chapter 7 AJAX summary

This chapter is a little bit older.

  1. Post is better for sending large amounts of data to the server.

  2. Get requests can be cached by the browser, and the Expires header sets how long the browser caches the request. Can be used with images that never change or other static data sets (JS, CSS, etc.)

  3. JSON is a lightweight and easy to parse data format written using JS objects and arrays. It not only has a small transfer size, but also has a fast parsing speed. JSON is the foundation of high-performance AJAX, especially when dynamic script injection is used.

Json should have been in use for a few years…

  1. Reduce the number of requests by merging JS and CSS files.
  2. Shorten the page load time, after the main content of the page is loaded, use AJAX to get those secondary files.

Chapter 8 Programming practice summary

  1. Avoid double evaluation: Avoid using the eval() and function() constructors to avoid the performance cost of double evaluation, as well as passing setTimeout() and setInterval() functions instead of strings as arguments.

    // Double count: Eval (' code ') function constructors --new function(' code ') setTimeout(' code ',100) and setInterval(' code ',100)Copy the code
  2. Create objects and arrays using direct quantities whenever possible. Direct quantities are faster to create and initialize than indirect quantities.

  3. Avoid reinventing the wheel. Save steps where you can.

  4. Js native methods will always be faster than any code you write.

Chapter 9: Building and deploying high-performance JS applications

The build and deployment process has a huge impact on the performance of JS-BASED Web applications. The most important steps in this process are:

  1. Merge and compress JS files. Can use Gzip compression, can reduce the volume of about 70%!

This is all work done during build, don’t wait until run time, webPack is also work done during build. 2. Cache JS files by correctly setting HTTP response headers, and avoid caching problems by adding time stamps to file names. 3. Use CDN to provide JS files; CDN not only improves performance, it also manages file compression and caching for you.

Chapter 10 Summary of Tools:

When a web page slows down, analyzing resources downloaded from the web and analyzing the performance of resources and scripts allows you to focus on the areas that need the most optimization.

  1. Use network analysis tools to find bottlenecks in loading scripts and other resources on your page. This will help you determine which scripts need lazy loading or further analysis.

    Examine the loading of images, stylesheets, and scripts and their impact on the overall loading and rendering of the page. So as to make targeted optimizationCopy the code
  2. Loading scripts as lazily as possible will speed up page rendering and give the user a better experience.

  3. Verify that the loading of scripts and other resource files has been optimized

    Here is the main file download speed from the server, such as server side configuration issues and so on. Chestnut: I've been poked by the back end. A JS file is 200K and it takes 50 seconds to download! Nginx does not enable acceleration configuration on the backend.Copy the code
  4. To test the running time of the script, subtract one Date instance from the other. The time difference is the running time of the script.

    let start=new Date(); // Your code let time=newDate()-start;Copy the code
  5. Control panels in major browsers like Chrome and Firefox already reflect performance issues. Careful analysis will reveal many problems. For example: resource loading, breakpoints, etc

The latter

In fact, I think the most valuable thing about the book is the details mentioned, such as:

1. Use the simple ‘+’ and ‘+=’ operators when combining strings.

str+='abc'+'efg; // More than 2 string concatenation will produce temporary string STR = STR +' ABC '+'efg'; // Speed up by 10%~40% is recommendedCopy the code

2. Avoid double evaluation: Avoid using the eval() and function() constructors to avoid the performance cost of double evaluation. Likewise, pass setTimeout() and setInterval() functions instead of strings as arguments.

// Double count: Eval (' code ') function constructors --new function(' code ') setTimeout(' code ',100) and setInterval(' code ',100)Copy the code

These things let us know what better practices are, what code can run faster, and let us develop better development habits.

The book is not too thick. If you are interested in its contents, you are advised to buy a copy and take a look at it at home.

The above 2018.1.9