JS overhead and how to shorten parsing time

1. JS overhead

Of all the fonts, HTML, and images, JavaScript is the most expensive resource. It is followed by parsing and compilation. Execution comes last.

In the case of the entire Reddit.com site, JS takes about a third of the time it takes to load a page. Even if users can see our page, they can’t interact with it because JS loads are blocked.

The Cost of Javascript

2. How to shorten the parsing time

① Code splitting Code is checked and loaded as needed.

The current access path needs to load what resources, we do not need to delay it, access time to load. Achieve the purpose of reducing js loading

Tree shaking code loses weight

For example, we simply refer to a function in loadsh and package that function into a bundle.

③ Reduce the workload of main thread

  • Avoid long tasks: The longer the task, the longer the block is occupied

  • Avoid interline scripts larger than 1KB: Interline scripts may be written to speed up rendering of the first screen. The rest is loaded through a Web file. Browsers cannot optimize for interline scripts.

  • RAF and rIC are used for time scheduling

3. There are three problems that we should pay attention to: happening, useful, usable

Two, V8 compilation principle

1. What is V8?

V8 is an open source JS engine developed by Google. It is currently used in The Chrome browser and Node.js to execute JS code. V8 is one of the JS virtual machines, which translates the JS programming language into machine language. SpiderMonkey, V8, JS Core and other popular JS engines in the market.

2. V8 executes the JS process

Description: source = abstract syntax tree = Bytecode= machine code

Note: The compilation process is optimized, and de-optimization may occur at run time

How does V8 implement JS

3. V8 optimization mechanics

  • Script flow

Scripts that are larger than 30KB are considered large enough to be parsed first (a separate thread is opened for parsing). It’s much more efficient to parse after all of this has been loaded, because you can just merge the previous parses.

  • Bytecode cache

Frequently used variables for caching

  • Lazy parsing

For functions, don’t parse the logic inside the function until you actually use the function.

Third, function optimization

1. Lazy parseing vs eager parseing

The advantage of lazy parsing is that if you don’t need parsing, you don’t have to allocate memory in the “heap” and create a syntax tree for it. Can improve the efficiency of loading JS as a whole.

But in reality, we sometimes need our functions to execute immediately. If we do lazy parsing first, and then find that we need to execute it immediately, we also need a hungry parsing, then the efficiency is halved. So we need to tell the parser that a function needs to be executed immediately and that starvation parsing is required.

Just add a parenthesis, and if the parenthesis gets removed during compression, you can use Optimize to retrieve the parenthesis. Const add = (a, b) => a+b; Const add = ((a, b) => a+b);Copy the code

Optimize the first load time with optimize.js

Optimize a JavaScript file for faster initial execution and parsing by wrapping all immediately executing functions or class executing functions in parentheses.

See Github: optimis-js

Fourth, object optimization

We tried to cater to the V8 parsing mechanism for code optimization.

  1. Initialize object members in the same order to avoid the adjustment of hidden classes. (If the order of hidden classes does not correspond, new hidden types will be generated and the previously generated hidden types cannot be reused.)
class RectArea { // HC0 constructor(l, w) { this.l = l; // HC1 this.w = w; // HC2}} const rect1 = new RectArea(3,4); // create hidden classes HC0, HC1, HC2 const rect2 = new RectArea(5,6); Const car1 = {color: 'red'}; // Same object structure, reuse all previous hidden classes const car1 = {color: 'red'}; // HC0 car1.seats = 4; // HC1 const car2 = {seats: 2}; // No reusable hidden classes, create HC2 car2.color = 'blue'; // Create HC3 with no reusable hidden classesCopy the code
  1. Avoid adding new attributes after instantiation
const car1 = {color: 'red'}; // In-objece const. Seats = 4; // The Normal/Fast property is stored in the property store, which needs to be found indirectly through the description array.Copy the code
  1. Try to use Array instead of array-like objects to show that the cost of conversion is less than the impact of optimization
Array. The prototype. The forEach. Call (arrObj, (the value, the index) = > {/ / than high efficiency the console on real Array. The log (` ${index} : ${value} `); }); const arr = Array.prototype.slice.call(arrObj, 0); Arr. ForEach ((value, index) => {console.log(' ${index}: ${value} '); });Copy the code
  1. Avoid reading more than the array length
function foo(array) { for (let i = 0; i <= array.length; If (array[I] > 1000) {// 1. Console. log(array[I]); console.log(array[I]); // Business invalid, error}}}Copy the code
  1. Avoid element type conversions
const array = [3, 2, 1]; / / PACKED_SMI_ELEMENTS array. Push (4.4); // PACKED_DOUBLE_ELEMENTSCopy the code

Reference article: What you may not know about V8 array optimization

5. HTML optimization

  1. Reduce ifames
  2. Compressed whitespace character
  3. Avoid deep nesting of nodes
  4. Avoid table layouts
  5. Remove the comments
  6. Semantic tag
  7. CSS and JavaScript should be linked out as much as possible,JS should be placed underneath, and don’t block DOM loading
  8. Delete element default attributes

Webpack integrates this functionality. (You can use htML-Minifile.)

Impact of CSS on performance

Look at the Recalculate Style in the waterfall diagram using the Devtool, which calculates the Render tree, then renders the page from the root node, attaching the CSS to the DOM, which is the time spent calculating the Style.

  1. Reduce CSS blocking

① Loading level: load the CSS styles used on the first screen as soon as possible, and delay the loading if not used, so that the impact can be reduced to a minimum.

(2) File size: reduce the file size as much as possible.

  1. Use GPU to complete animation, both using composite layers.
  2. Use the contain property.

Tell the browser that I have nothing to do with the outside, only change the elements inside me, no backflow, no layout recalculation.4. The font – the display properties

Show the text on the page first to reduce the problem of flashing text