Some potential rules of js (2)

Macro tasks and micro tasks

Adopting the terminology of the JSC engine, we call the tasks initiated by the host macro tasks and the tasks initiated by the JavaScript engine micro tasks.

The JavaScript engine waits for the host environment to allocate macro tasks. In the operating system, the waiting behavior is usually an event loop, so in Node terminology, this part is also called the event loop. In the underlying C/C++ code, this event loop is a loop running in a separate thread.

The queue of macro tasks is equivalent to the event loop.

In macro tasks, JavaScript's Promise will also generate asynchronous code. JavaScript must ensure that these asynchronous codes are completed in a macro task. Therefore, each macro task also contains a micro task queue.

Statement execution process (Completion Record)

We know that some statements are executed in order, and some statements block execution. So what causes this?

Let's take a look at the completion status of js statement execution. The completion status of JavaScript statement execution is represented by a standard type: Completion Record.

Completion Record represents the result after a statement is executed. It has three fields:

  • [[type]] represents the completion type, including break continue return throw and normal; if the returned type is normal, then the statements will be executed sequentially.
  • [[value]] represents the return value of the statement. If the statement does not have one, it is empty; only expression statements will produce [[value]].
  • [[target]] represents the target of the statement, usually a JavaScript tag. When in a loop statement, combining break/continue can break out of multiple loops.
 outer: while(true) {inner: while(true) {break outer;}
}

console.log("finished") 

You can add a tag before any js statement.

 firstStatement: var i = 1; 

The effect produced by the combination of control statements and the four types of break, continue, return, throw and control statements.

  • Consumption ends in the current statement.
  • Penetration means continuing to execute the next statement.

grammar

Grammar = Lexicon + Grammar.

Lexical

Input in JavaScript source code can be classified like this:

WhiteSpace whitespace characters

LineTerminator newline character

Comment Comment

Token pronunciation

  • IdentifierName Identifier name, a typical case is the variable name we use, note that the keywords are also included here.
  • Punctuator symbols, symbols like operators and braces that we use.
  • NumericLiteral Numeric literals are the numbers we write. Why 12.toStringis an error reported?

Decimal Number can contain decimals, and the parts before and after the decimal point can be omitted, but not both at the same time. 12.treated as a word. If we want the expression to work properly, we can make .it a word.

 12. toString() 
  • StringLiteral string literal is the literal that we enclose in single quotes or double quotes.

Other characters in the string that must be escaped are \ and all newline characters.

  • Template string template, a literal value enclosed in backticks `.
  • RegularExpressionLiteral

Regular expressions have their own grammatical rules, and in the lexical stage, they are only briefly parsed.

Whether the statement requires a semicolon

The rules for automatically inserting semicolons are actually independent of all grammatical production definitions. Its rules are very simple, with only three rules.

  • If there is a newline character and the next symbol is ungrammatical, try inserting a semicolon.
  • If there is a newline character, and the grammar stipulates that there cannot be a newline character here, then a semicolon is automatically inserted.
  • At the end of the source code, if a complete script or module structure cannot be formed, a semicolon is automatically inserted.

no LineTerminator here rule

This rule is closely related to the second rule for automatically inserting semicolons.

Scripts and modules

Scripts can be imported and executed by the browser or node environment, while modules can only be imported and executed by JavaScript code.

Conceptually, we can think of scripts as active JavaScript code segments, which are codes that control the host to complete certain tasks; while modules are passive JavaScript code segments, which are libraries waiting to be called.

Directly importing a module only ensures that the module code is executed, and the module that references it cannot obtain any information about it. Import with from means to introduce part of the information in the module and turn them into local variables.

Through export defaultthe exported value, the variables in the imported file are not bound in real time. Variable changes in the exported file will not affect changes in the imported variables.

Statement promotion

In the preprocessing stage, var and function declarations can penetrate all statement structures. It only recognizes three grammatical structures: script, module and function body.

The difference between function declaration hoisting and var variable declaration hoisting

The function declaration can pass through if statements and other statements, but it only creates a variable with the same name globally and assigns it to undefined, and does not promote the function body.

 console.log(foo); // undefinedif(true) {function foo(){}}// 因为一般函数都是整体提升的。 
 var a = 1;function foo() {console.log(a); // undefinedif(false) {var a = 2;}}foo(); 

Parse HTML

Compilation stage. The html tags will be split into tokens (representing the smallest meaningful unit), and the types are only the beginning of the tag, attributes, end of the tag, comments, and CDATA nodes.

To implement word segmentation, a state machine is used again. Using a state machine for lexical analysis actually separates the "characteristic characters" of each word into independent states one by one, and then links the characteristic characters of all words together to form a connected graph structure. Each of the state functions returns a state function to perform state migration.

After dividing the html elements into several words, we can build the dom tree. This process is implemented using the stack. We add each parsed word to the stack, and when all input is received, the top of the stack is the final root node.

For Text nodes, we need to merge adjacent Text nodes. Our approach is to check whether the top of the stack is a Text node when the word (token) is pushed onto the stack. If so, merge the Text nodes.

typesetting.

  • Browsers generally lay out the rows within the row first, then determine the position of the row, and calculate the layout position of the in-row box and text based on the position of the row.
  • The block-level box is relatively simple. It always occupies a whole row by itself. Just calculate the height in the cross-axis direction.
  • Floating elements are typesetting. Float elements are very special. The browser processes floats by first arranging them into the normal flow, and then moving them to the far left/right of the typesetting width (actually the front and back of the main axis).
  • Absolutely positioned elements. An independent typesetting mode that has nothing to do with normal flow. Just find the position of its parent non-static element layer by layer.

render.

The process of rendering in the browser is to turn the box corresponding to each element into a bitmap. The elements here include HTML elements and pseudo-elements. One element may correspond to multiple boxes (such as inline elements, which may be divided into multiple lines). Each box corresponds to a bitmap.

During the rendering process, child elements will not be drawn to the rendered bitmap. In this way, when the relative positions of parent and child elements change, it can be ensured that the rendering results can be cached to the greatest extent and reduce re-rendering.

synthesis.

The process of compositing is to create a "composited bitmap" (we call it a composite layer) for some elements, and render some sub-elements onto the composite bitmap.

draw.

The drawing process actually draws the composite bitmap to the screen in sequence according to z-index.

DOM API

The DOM API will roughly include 4 parts.

  • Node: Node-related API in the DOM tree structure.
  • Events: triggering and monitoring event-related APIs.
  • Range: API related to operating text range.
  • Traversal: API required for traversing DOM.

node

Element relationship in DOM tree api

  • parentNode
  • childNodes
  • firstChild
  • lastChild
  • nextSibling
  • previousSibling

API for manipulating DOM trees

  • appendChild
  • insertBefore
  • removeChild
  • replaceChild

Some high-level APIs

  • compareDocumentPosition is a function that compares the relationship between two nodes.
  • contains Function that checks whether a node contains another node. This method is generally used to make some click judgments and then close some DOM functions.
  • isEqualNode checks whether two nodes are identical.
  • isSameNode checks whether two nodes are the same node. In fact, "===" can be used in JavaScript.
  • cloneNode copies a node. If the parameter true is passed in, a deep copy will be made along with the child elements.

Create DOM API

  • createElement
  • createTextNode
  • createCDATASection
  • createComment
  • createProcessingInstruction
  • createDocumentFragment
  • createDocumentType

API for manipulating attributes

  • getAttribute
  • setAttribute
  • removeAttribute
  • hasAttribute If you like to access attributes like properties, you can also use the attributes object. For example, document.body.attributes.class = "a" is equivalent to document.body.setAttribute("class", "a").

find element api

  • querySelector
  • querySelectorAll
  • getElementById
  • getElementsByName
  • getElementsByTagName
  • getElementsByClassName

We need to note that the performance of getElementById, getElementsByName, getElementsByTagName, and getElementsByClassName is higher than that of querySelector.

The newly added nodes will be added to non querySelector- querySelectorAllqueried objects.

Traverse

  • createNodeIterator
  • createTreeWalker

Range

Range API represents a range on HTML. This range is based on text as the smallest unit, so Range does not necessarily include complete nodes.

Please see here for details

location in DOM

Global size information

  • getClientRects(). Returns a list containing the client rectangular area occupied by each box corresponding to the element. Here each rectangular area can use x, y, width, height to obtain its position and size.
  • getBoundingClientRect(). It returns the rectangular area wrapped by all boxes corresponding to the element. It should be noted that the area obtained by this API will include the child element area when overflow is visible.

The rectangular areas obtained by these two APIs are coordinates relative to the viewport, which means that these areas are affected by scrolling.

event

The origin of event capture?

When we operate elements, we do it through input devices. The click event comes from the touch screen or mouse. There is no position information for mouse clicks, but the general operating system will calculate it based on the accumulation of displacement. Just like the touch screen, it provides a coordinate for browsing. device. The process of converting this coordinate into an event on a specific element is the capture process.

It is recommended to use the bubbling and capturing mechanism in this way: the bubbling mode is used by default. When developing components, you can use the capturing mechanism when you encounter a behavior that requires a parent element to control the behavior of a child element.

The event handling function does not have to be a function, it can also be a JavaScript object with a handleEvent method.

var o = {handleEvent: event => console.log(event)
}
document.body.addEventListener("keydown", o, false); 

Custom events. Events in the DOM API are not available for normal objects, so unfortunately we can only use custom events on DOM elements.

 var evt = new Event("look", {"bubbles":true, "cancelable":false});document.dispatchEvent(evt); // 调用自定义事件 

Performance optimization

at last

We have compiled 75 JS high-frequency interview questions, and provided answers and analysis. This can basically guarantee that you can cope with the interviewer's questions about JS.



Friends in need can click on the card below to receive it and share it for free

Guess you like

Origin blog.csdn.net/web2022050901/article/details/129805360