This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

preface

Hello, everyone, I am Lin Sanxin, the basis is the premise of progress, last article, I shared with you my usual record of the work of 50 JS basic knowledge points, today to share with you, I this year, work encountered 50 JS advanced knowledge points!!

knowledge

1, the difference between undeclared and undefined?

  • Undefined: declares a variable but does not assign a value
  • Undeclared: used without declaring variables
var a; //undefined
b;    // b is not defined
Copy the code

2, Let & const vs. var

  • Var has variable promotion, which can repeatedly declare the same variable and the declared variable can be changed
  • There is no variable promotion in LET, and the same variable cannot be repeatedly declared. All declared variables can be changed
  • Const has no promotion, cannot declare the same variable repeatedly, declare the basic data type is unchangeable, reference type modifiable attributes, cannot declare variables without assigning values

3. Temporary dead zones

var a = 100;

if(1){
    a = 10;
    // If a is declared let/const in the current block scope, assigning a value of 10 to a will only look for variable A in the current scope.
    // Console Error: A is not defined
    let a = 1;
}
Copy the code

4. What are the methods to get DOM elements

methods describe The return type
document.getElementById(id) Get the DOM by id Dom objects that match the criteria
document.getElementsByTagName(tagName) Get the DOM by tag name Class array of all dom objects that match the criteria
document.getElementsByClassName(class) Get the DOM through class Class array of all dom objects that match the criteria
document.getElementsByName(name) Get the DOM from the tag’s attribute name Class array of all dom objects that match the criteria
Document. querySelector Get the DOM through the selector The first DOM object that meets the criteria
Document. QuerySelectorAll (selectors) Get the DOM through the selector Class array of all dom objects that match the criteria

5. What are the methods for manipulating DOM elements

The title describe
createElement Create a label node
createTextNode Create a text node
cloneNode(deep) Copy a node, along with its attributes and values, or if deep is true, along with the descendant node, if not or false, only the current node is copied
createDocumentFragment Create a document shard node
appendChild Append child element
insertBefore Insert the element in front
removeChild Deleting child elements
replaceChild Replace child element
getAttribute Gets the attributes of the node
createAttribute Create a properties
setAttribute Setting Node Properties
romoveAttribute Deleting node Attributes
element.attributes Generates the property into a class array object

6. What are the types of DOM?

12

Element Node node.element_node (1) Attribute Node Node.ATTRIBUTE_NODE(2) Text Node node.text_node (3) CDATA Node node.cdatA_section_node (4) Entity reference name Node node.entry_reference_node (5) Entity name Node node.entity_node (6) Processing instruction Node node.processing_instruction_node (7) Comment Node Node.COMMENT_NODE(8) Document Node node.document_node (9) Document type Node node.document_type_node (10) Document fragment Node Node.document_fragment_node (11) DTD declaration Node node.notation_node (12)Copy the code

JS scope and scope chain

What is scope?

In Javascript, scopes are divided into global scopes and function scopes

  • Global scope: Code can be accessed anywhere in the program, and the window object’s built-in properties belong to the global scope
  • Function scope: can only be accessed in fixed code snippets

A scope has a hierarchy, which depends on the scope in which the function is created. As above, fn scope creates bar function, so “FN scope” is the superior of “bar scope”.

The greatest use of a scope is to isolate variables. Variables of the same name in different scopes do not conflict.

What is a scope chain?

Normally, a variable takes a value in the scope of the function that created it

But if no value is found in the current scope, the chain is called the scope chain

var x = 10;

function fn(){
    console.log(x);
}

function show(f){
    var x = 20;
    f();    / / 10
}

show(fn);
Copy the code

8. What is the difference between an array splice and a slice?

methods parameter describe
splice splice(start, num, item1, item2, …) Select num from start index and insert item1, item2 into original array
slice splice(start, end) If there is no end, the array is truncated to the last element to the left without affecting the original array

What is the difference between substr and substring?

methods parameter describe
substr substr(start,length) Returns a substring of length starting at the start position
substring substring(start,end) Returns a substring from start to end (without end)

10. What is better than indexOf includes?

Includes checks NaN. IndexOf does not. NaN is matched internally with number. isNaN

11. What is the output of the following code?

for(var i = 0; i < 3; i++){
  setTimeout(function(){
      console.log(i);   
  },0); 
};
Copy the code

Answer: 3,3,3

The solution

for(let i = 0; i <= 3; i++){
  setTimeout(function(){
      console.log(i);   
  },0); 
};
/ / 0 1 2
Copy the code
for (var i = 0; i < 3; i++) {
  (function(i) {
    setTimeout(function () {
      console.log(i);
    }, 0, i)
  })(i)
};
/ / 0 1 2
Copy the code

12. What is Promise? What problem was solved?

What’s the use?

  • 1. Fix callback hell
  • 2. Improved code readability
  • 3. You can trust Promise to change its state only once and irrevocably

Recommended reading

  • What is: recommend ruan yifeng big man’s article Promise object
  • Principle: I recommend this handwritten Promise principle, the most accessible version!! [Reading: 1.2W, Likes: 466]

13, What is async/await? What problem was solved?

I summarize async/await as a syntactic sugar for generator + Promise, which executes asynchronous code synchronously

Recommended reading

  • Ruan Yifeng’s article async and await
  • The principle of async/await: I recommend this 7 pictures of async/await principle which can be done in 20 minutes! Why is it taking so long? [Reading: 2.1W, Thumbs up: 630]

14. What regular expressions are commonly used?

With these 25 regular expressions, code efficiency increases by 80%.

What are the methods of JS lazy loading?

  • 1.<script async src="script.js"></script>: Add async to script tags and the loading and rendering of subsequent document elements will changescript.jsLoad and execute in parallel (asynchronously)
  • 2,<script defer src="script.js"></script>: Add the defer attribute to the script tag, and the process of loading subsequent document elements will be as followsscript.jsThe load is done in parallel (asynchronously), howeverscript.jsAfter all elements have been parsed,DOMContentLoadedThe event is completed before firing
  • Create a script tag dynamically: waitDOMContentLoadedWhen the event is triggered, a script tag is generated and rendered to the page
  • 4. SetTimeout timer delays code execution

Why can the new operator create an instance object?

Analyze the whole process of new:

  • Create an empty object
  • 2. Inherit the constructor prototype
  • 3. This points to obj and calls the constructor
  • 4. Return object

A simple implementation of new:

function myNew (fn, ... args) {
    // Step 1: Create an empty object
    const obj = {}

    // Step 2: Inherit the constructor prototype
    obj.__proto__ =  fn.prototype

    // Step 3: this points to obj and calls the constructor
    fn.apply(obj, args)


    // Step 4: Return the object
    return obj
}
Copy the code

17. What is document fragmentation?

  • What is it: a container for temporarily storing created DOM elements, useddocument.createDocumentFragment()create
  • What does it do: Add a large number of elements that need to be added to the document fragment first, and then add the document fragment where it needs to be inserted, greatly reducing DOM manipulation and improving performance

example

var oFragmeng = document.createDocumentFragment(); 


for(var i=0; i<10000; i++) {var op = document.createElement("span"); 

    var oText = document.createTextNode(i); 

    op.appendChild(oText); 

    // Attach to the document fragment first

    oFragmeng.appendChild(op);  

} 


// Add to document one last time

document.body.appendChild(oFragmeng); 
Copy the code

How can ASYNc /await detect an error?

Recommend this async await for more elegant error handling.

19. What are macro tasks and micro tasks?

Macro task

# The browser Node
I/O
setTimeout
setInterval
setImmediate
requestAnimationFrame

Micro tasks

# The browser Node
Promise.prototype.then catch finally
process.nextTick
MutationObserver

20. What is the execution sequence of macro and micro tasks? Tell me something about the EventLoop?

How about setTimeout+Promise+Async output order? It’s simple!

21, Object.defineProperty(target, key, options), options can pass what parameter?

  • Value: Sets the initial value for target[key]
  • Get: Triggered when target[key] is invoked
  • Set: Triggered when the target[key] is set
  • Writable: Specifies whether target[key] can be overwritten. The default value is false
  • Enumerable: Specifies whether a key appears in the target enumeration property. It defaults to false
  • The default is false. For details, see Object. DefineProperty and works without any additional information, exercising any additional control system

What is anti shake? What is throttling?

operation describe scenario
Image stabilization Trigger an event frequently, but only once. Last time is final 1, the computer screen time, every time the computer recalculates the time

2, input box changes frequently trigger events can be added to shake

3. Frequent clicking of the button to submit the form can add anti-shaking
The throttle Trigger an event frequently, but only once in a while 1, rolling frequent request list can be throttled

2. Long press the mouse in the game, but the action is done every once in a while

23. What are higher-order functions? Simple implementation of one?

Higher-order function: higher-order function JavaScript functions actually refer to a variable. Since variables can point to functions and arguments to functions can accept variables, a function can accept arguments to another function, which is called a higher-order function.

// A simple higher-order function
function add(x, y, f) {
    return f(x) + f(y);
}

// Verify with code:
add(-5.6.Math.abs); / / 11
Copy the code

Arrays like Map, Reduce, and filter are higher-order functions

24. What is a function Coriolization? Simple implementation of one?

Currying, English: Currying, is a technique of converting a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function), and returning a new function that takes the remaining arguments and returns a result.

// The normal add function
function add(x, y) {
    return x + y
}

/ / after Currying
function curryingAdd(x) {
    return function (y) {
        return x + y
    }
}

add(1.2)           / / 3
curryingAdd(1) (2)   / / 3
Copy the code

benefits

  • 1. Parameter multiplexing
// Normal rege.test (TXT)

// Common case
function check(reg, txt) {
    return reg.test(txt)
}

check(/\d+/g.'test')       //false
check(/[a-z]+/g.'test')    //true

/ / after Currying
function curryingCheck(reg) {
    return function(txt) {
        return reg.test(txt)
    }
}

var hasNumber = curryingCheck(/\d+/g)
var hasLetter = curryingCheck(/[a-z]+/g)

hasNumber('test1')      // true
hasNumber('testtest')   // false
hasLetter('21212')      // false
Copy the code
  • 2. Delay execution

In fact, function.prototype. bind is an example of coriification

function sayKey(key) {
  console.log(this[key])
}
const person = {
  name: 'Sunshine_Lin'.age: 23
}
// Call is not coriolization
sayKey.call(person, 'name') // Output Sunshine_Lin immediately
sayKey.call(person, 'age') // Output 23 immediately

// Bind is currified
const say = sayKey.bind(person) / / does not perform
// Execute again
say('name') // Sunshine_Lin
say('age') / / 23
Copy the code

25, What is compose? Simple implementation of one?

Simple compose function

const compose = (a , b) = > c= > a( b( c ) );
Copy the code

Example: Count words

//
console.log(len(space('i am linsanxin'))) / / 3
console.log(len(space('i am 23 year old'))) / / 6
console.log(len(space('i am a author in juejin'))) / / 7


/ / compose of writing
const compose = (. fn) = > value= > {
  return fn.reduce((value, fn) = > {
    return fn(value)
  }, value)
}
const computedWord = compose(space, len)
console.log(computedWord('i am linsanxin')) / / 3
console.log(computedWord('i am 23 year old')) / / 6
console.log(computedWord('i am a author in juejin')) / / 7
Copy the code

26. What are the differences between arrow functions and ordinary functions?

  • 1. Arrow functions are not constructors. New cannot be used
  • 2. Arrow functions do not have their own this
  • Arrow functions don’t have arguments objects
  • Arrow functions have no prototype objects

27. The application scenario of Symbol?

Application Scenario 1: Use Symbol for object attribute names

Normally the properties of our objects are strings

const obj = {
  name: 'Sunshine_Lin'.age: 23
}
console.log(obj['name']) // 'Sunshine_Lin'
console.log(obj['age']) / / 23
Copy the code

You can also use Symbol as the property name

const gender = Symbol('gender')
const obj = {
  name: 'Sunshine_Lin'.age: 23,
  [gender]: 'male'
}
console.log(obj['name']) // 'Sunshine_Lin'
console.log(obj['age']) / / 23
console.log(obj[gender]) / / male
Copy the code

But the Symbol attribute is not enumerated, which is why the Symbol attribute is excluded when json.stringfy (obj)

console.log(Object.keys(obj)) // [ 'name', 'age' ]
for(const key in obj) {
  console.log(key) // name age
}
console.log(JSON.stringify(obj)) // {"name":"Sunshine_Lin","age":23}
Copy the code

In fact, it is not impossible to obtain the Symbol attribute.

/ / method
console.log(Object.getOwnPropertySymbols(obj)) // [ Symbol(gender) ]
/ / method 2
console.log(Reflect.ownKeys(obj)) // [ 'name', 'age', Symbol(gender) ]
Copy the code

Application Scenario 2: Use symbols instead of constants

There are the following scenarios

/ / assignment
const one = 'oneXin'
const two = 'twoXin'

function fun(key) {
  switch (key) {
    case one:
        return 'one'
      break;
    case two:
        return 'two'
      break; }}Copy the code

If the number of variables is small, this is fine, but if the number of variables is large, assignment naming is annoying

const one = Symbol(a)const two = Symbol(a)Copy the code

Application Scenario 3: Use Symbol to define private attributes of a class

In the following example, the PASSWORD attribute is not available in the instance

class Login {
  constructor(username, password) {
    const PASSWORD = Symbol(a)this.username = username
    this[PASSWORD] = password
  }
  checkPassword(pwd) { return this[PASSWORD] === pwd }
}

const login = new Login('123456'.'hahah')

console.log(login.PASSWORD) / / an error
console.log(login[PASSWORD]) / / an error
console.log(login[PASSWORD]) / / an error
Copy the code

28, AMD and CMD difference?

modular On behalf of the application The characteristics of
AMD require.js 1, AMD API default when a multiple use

2, rely on the front, asynchronous execution
CMD sea.js 1. The API of CMD is strictly differentiated and advocates single responsibility

2. Rely on nearby, load as needed, and execute synchronously

Commonjs and ES6 Module

Answer from alibaba Taoshi technology front end team:

  • 1, Commonjs is copy output, ES6 modularity is reference output
  • 2, Commonjs is run time loading, ES6 modularity is compile time output interface
  • 3, Commonjs is a single value export, ES6 modular can export multiple values
  • 4, Commonjs is a dynamic syntax that can be written in the function body, ES6 modular static syntax can only be written at the top level
  • 5, Commonjs this is the current modular, ES6 modular this is undefined

CommonJS modules are different from ES6 modules

30. Why doesn’t Commonjs work in browsers

var math = require('math');

math.add(2.3);
Copy the code

The second line math.add(2, 3) runs after the first line require(‘math’), so must wait for math.js to finish loading. That is, if it takes a long time to load, the entire application will just sit there and wait.

This is not a problem on the server because all modules are stored on the local hard disk and can be loaded synchronously, and the wait time is the hard disk read time. For browsers, however, this is a big problem because modules are on the server side and the wait time can be long depending on the speed of the network, leaving the browser in a state of “suspended animation”.

Therefore, browser-side modules cannot be synchronous, they can only be asynchronous. This is the background from which the AMD specification was born.

What are the common es6-ES12 grammars?

Look at me. This is a good foundation, okay? Summary of 38 ES6-ES12 development tips, but to see how much you can get? [reading: 4W, likes: 1.8K]

32, (a == 1 && a == 2 && a == 3)

(a == 1 && a == 2 && a == 3)

What is the length of the function?

Look at the question that 95% of the people in this article can’t answer: What is the length of the function?

MUL function in JS

MUL represents a simple multiplication of numbers. In this technique, one value is passed as an argument to a function that returns another function, passes the second value to the function, and then repeats. For example, xyz can be expressed as

const mul = x= > y= > z= > x * y * z

console.log(mul(1) (2) (3)) / / 6
Copy the code

Depth traversal breadth traversal difference?

For an algorithm it’s just time for space space for time

  • 1. Depth-first does not need to remember all nodes, so it occupies a small space, while breadth-first requires that all nodes occupy a large space
  • 2, depth first backtracking operation (no road to go back), so relatively speaking, a little longer time
  • Depth-first is in the form of a stack, that is, first in, last out
  • Breadth-first is in the form of a queue, that is, first-in, first-out

What are the design patterns in JS?

I recommend this article: JavaScript Design Patterns

How does forEach jump out of the loop?

ForEach cannot break or return a loop. Why? ForEach’s callback function, as those of you who have implemented forEach know, forms a scope in which a return does not exit, but is treated as a continue

So how do you get out of the loop? You can use a try catch

  function getItemById(arr, id) {
        var item = null;
        try {
            arr.forEach(function (curItem, i) {
                if (curItem.id == id) {
                    item = curItem;
                    throw Error(a); }})}catch (e) {
        }
        return item;
    }
Copy the code

39, how to redirect a page to another page in JS?

  • 1, use the location. Href: window. The location. The href = “www.onlineinterviewquestions.com/”

  • 2, use the location. The replace: window. The location. The replace (” www.onlineinterviewquestions.com/;” );

40, implement a common JS native method?

30 JS native methods implemented in 3 hours

What are the mouse events?

Note: Right mouse button properties on the event object, corresponding to 1, 2, 3

The event instructions
click When the user focuses on the button and presses Enter, it will also trigger
dbclick Double-click the left mouse button. The right mouse button is invalid
mousedown Any button of single mouse is triggered
mouseout Triggered when the mouse pointer is over an element and is about to move out of the element boundary
mouseover Triggered when the mouse pointer moves from one element to another
mouseup Triggered when the mouse pointer moves from one element to another
mouseover Triggered when any mouse button is released
mousemove Occurs continuously when the mouse is over an element
mouseenter Triggered when the mouse enters an element boundary
mouseleave Triggered when the mouse moves away from an element boundary

What are the keyboard events?

Note: The keyCode property on the Event object is the ASCLL value of the key pressed, which can be distinguished from the key pressed. ASCLL table in this ASCII code list, ASCII code comparison table

The event instructions
onkeydown Triggered when a keyboard key is pressed
onkeyup Triggered when a keyboard key is released
onkeypress Trigger when a key is pressed, do not listen for function keys such as CTRL, Shift

The coordinates of mouse events in JS?

attribute instructions compatibility
offsetX Position the X-axis starting from the upper-left corner of the current target element All compatible except Mozilla
offsetY Position the Y-axis starting from the upper left corner of the current target element All compatible except Mozilla
clientX Locate the X-axis starting from the upper left corner of the browser’s visual window All compatible except Safari
clientY Locate the Y-axis starting from the upper left corner of the browser’s visual window All compatible except Safari
pageX Starting from the upper left corner of the Doument object, locate the X-axis coordinates All compatible except IE
pageY Take the upper left corner of the Doument object as the origin to locate the Y-axis coordinates All compatible except IE
screenX Take the top left corner of the computer screen as the origin, locate the X-axis coordinates (multiple screens will affect) Fully compatible with
screenY Take the top left corner of the computer screen as the origin to locate the Y-axis coordinates Fully compatible with
offsetX The X-axis coordinates are located from the upper left corner of the target element at the current time All compatible except Mozilla
layerX The top left corner of the nearest absolute positioned parent element (if not, the Document object) is the element and positions the X-axis Mozilla and Safari
layerY The top left corner of the nearest absolute positioned parent element (if not, the Document object) is the element and positions the Y-axis Mozilla and Safari

What are the dimensions of an element view in JS?

attribute instructions
offsetLeft Gets the distance of the current element to the left direction of the positioned parent node
offsetTop Gets the distance of the current element to the top direction of the positioned parent node
offsetWidth Get the current element width + left/right padding + left/right border-width
offsetHeight Gets height + padding + border-width for the current element
clientWidth Gets the current element width + left and right padding
clientHeight Gets height + upper and lower padding for the current element
scrollWidth The true width of the current element’s content, the box’s clientWidth if the content does not exceed the box’s height
clientHeight The true height of the current element content, clientHeight of the box if the content does not exceed the height of the box

45, The various dimensions of the Window view?

attribute instructions
innerWidth InnerWidth The width of the viewable area of the browser window (excluding the browser console, menu bar, and toolbar)
innerHeight InnerWidth The height of the viewable area of the browser window (excluding the browser console, menu bar, and toolbar)

46, Document Document view dimensions?

attribute instructions
document.documentElement.clientWidth Width of browser window viewable area (excluding browser console, menu bar, toolbar, scroll bar)
document.documentElement.clientHeight Height of viewable area of browser window (excluding browser console, menu bar, toolbar, scrollbar)
document.documentElement.offsetHeight Get the height of the entire document (including the body margin)
document.body.offsetHeight Get the height of the entire document (excluding the body margin)
document.documentElement.scrollTop Returns the distance in the scrolling top direction of the document (the value changes when the window is scrolling)
document.documentElement.scrollLeft Returns the scrolling left direction of the document (value changes when the window is scrolling)

Nine advanced JavaScript methods

1. getBoundingClientRect

1.1 what is

Element. GetBoundingClientRect () method returns the Element size and its position relative to the viewport. Return an object with eight attributes: left, right, top, bottom, width, height, x, y

1.2 compatibility

It works in almost every browsergetBoundingClientRect

1.3 Determine whether the element is visible

This is the scenario where getBoundingClientRect is most commonly used to determine whether an element appears intact in the viewport

// html

<div id="box"></div>

body {
       height: 3000px;
       width: 3000px;
      }

#box {
       width: 300px;
       height: 300px;
       background-color: red;
       margin-top: 300px;
       margin-left: 300px;
    }
    
// js

const box = document.getElementById('box')
        window.onscroll = function () {
            // Box is printed true only if it appears completely in the viewport, otherwise false
            console.log(checkInView(box))
        }

function checkInView(dom) {
        const { top, left, bottom, right } = dom.getBoundingClientRect()
        console.log(top, left, bottom, right)
        console.log(window.innerHeight, window.innerWidth)
        return top >= 0 &&
                left >= 0 &&
                bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
                right <= (window.innerWidth || document.documentElement.clientWidth)
        }
Copy the code

According to this use, we can achieve: lazy loading and infinite scrolling

1.4 weaknesses?

  • 1, every scroll has to be recalculated, high performance consumption
  • 2, causeRedraw the reflux

2. IntersectionObserver

2.1 what is

The IntersectionObserver interface provides a way to asynchronously observe the intersecting status of a target element with its ancestor element or top-level document viewport. Ancestor elements and viewports are called roots

In plain English, IntersectionObserver is used to monitor the intersecting status of an element and its viewport. What are the cross states? If I scroll down and only half of the elements are in the viewport, then the element and viewport will cross at 50% :

2.2 usage

// Receive two arguments callback option
var io = new IntersectionObserver(callback, option);

// Start observing (multiple elements can be observed)
io.observe(document.getElementById('example1'));
io.observe(document.getElementById('example2'));

// Stop observing an element
io.unobserve(element);

// Close the viewer
io.disconnect();
Copy the code

2.3 the callback

Callbacks are typically triggered in two ways. Either the target element is just inside the viewport (visible) or it is completely out of the viewport (invisible).

var io = new IntersectionObserver(
  entries= > {
    console.log(entries); });Copy the code

The parameters of the callback function (entries) is an array, each member is a IntersectionObserverEntry object. For example, if the visibility of two observed objects changes at the same time, the Entries array will have two members.

2.4 IntersectionObserverEntry object

{
  time: 3893.92.rootBounds: ClientRect {
    bottom: 920.height: 1024.left: 0.right: 1024.top: 0.width: 920
  },
  boundingClientRect: ClientRect {
     // ...
  },
  intersectionRect: ClientRect {
    // ...
  },
  intersectionRatio: 0.54.target: element
}
Copy the code

Attribute parsing:

  • time: The time at which visibility changes, a high-precision timestamp in milliseconds
  • target: The object element being observed is a DOM node object
  • rootBounds: information about the rectangular region of the root element,getBoundingClientRect()Method, if there is no root element (that is, scrolling directly with respect to the viewport)null
  • boundingClientRect: Information about the rectangular region of the target element
  • intersectionRect: Information about the area where the target element intersects with the viewport (or root element)
  • intersectionRatio: Visibility ratio of the target element, i.eintersectionRectAccount forboundingClientRectIs fully visible1Is less than or equal to completely invisible0

2.5 the option

Mention the two more important properties of the second option parameter: threshold and root

First, threshold:

The threshold attribute determines when the callback function is triggered. It is an array and each member is a threshold value, which defaults to [0], i.e., intersectionRatio triggers the callback function when it reaches 0.

new IntersectionObserver( entries => {/* ... */}, {threshold: [0, 0.25, 0.5, 0.75, 1]});Copy the code

The user can customize the array. For example, [0, 0.25, 0.5, 0.75, 1] means that the callback is triggered when the target element is 0%, 25%, 50%, 75%, 100% visible.

Back to root:

The IntersectionObserver API supports intra-container rolling. The root attribute specifies the container node on which the target element is located (the root element). Note that the container element must be the ancestor node of the target element.

new IntersectionObserver( entries => {/* ... }, {threshold: [0, 0.25, 0.5, 0.75, 1], root: document.getelementById ('#container')});Copy the code

2.6 Complete Examples

body {
            height: 3000px;
            width: 3000px;
        }

#box1 {
            width: 300px;
            height: 300px;
            background-color: red;
            margin-top: 100px;
            margin-left: 300px;
        }
#box2 {
            width: 300px;
            height: 300px;
            background-color: red;
            margin-top: 100px;
            margin-left: 300px;
        }
<div id="box1"></div>
<div id="box2"></div>

const io = new IntersectionObserver(entries= > {
            console.log(entries)
        }, {
            threshold: [0.0.25.0.5.0.75.1]
            // root: xxxxxxxxx
        })
io.observe(document.getElementById('box1'))
io.observe(document.getElementById('box2'))
Copy the code

2.7 Application Scenarios

  • 1, can be likegetBoundingClientRectThat way you can determine if the element is in the viewport, and the advantage is that it doesn’t cause redraw backflow
  • 2. Similarly, with the first function, you can do itLazy loading and infinite scrollingThe function of

2.8 disadvantages

If you want to be compatible with IE, forget about this API…

3. createNodeIterator

3.1 Get to know the API

How do I know this API? I was asked in the interview: Tell me how to iterate through all the elements in the output page. My first thought would be to use a loop recursion to output. Interviewer: All right, go home and wait for news.

Later I went home and found out about the createNodeIterator API

3.2 the problem solving

How do you use createNodeIterator to iterate over all the elements on a page?

const body = document.getElementsByTagName('body') [0]
    const it = document.createNodeIterator(body)
    let root = it.nextNode()
    while(root) {
        console.log(root)
        root = it.nextNode()
    }
Copy the code

Find a website to test:

3.3 Detailed Parameters

Detailed parameters can be seen here, very detailed

3.4 compatibility

A piece of green ah, dare to rest assured use!

4. getComputedStyle

4.1 what is

The window.getComputedStyle () method returns an object that reports the values of all the CSS properties of the element after the active stylesheet is applied and any basic calculations that those values may contain are parsed. Private CSS property values can be accessed through apis provided by the object or simply indexed using CSS property names.

window.getComputedStyle(element, pseudoElement)
Copy the code
  • element: required, the element to get the style.
  • pseudoElement: Optional, pseudo-class elements. If you do not query pseudo-class elements, you can ignore them or pass null.

4.2 the use of

Get the style with getPropertyValue

// html
#box {
            width: 300px;
            height: 300px;
            background-color: yellow;
    }
    
<div id="box"></div>

const box = document.getElementById('box')
const styles = window.getComputedStyle(box)
// Use getPropertyValue to get the style
const height = styles.getPropertyValue("height")
const width = styles.getPropertyValue("width")
console.log(height, width) / / "300 px" '300 px'
Copy the code

4.3 compatibility

It’s all green. Use with confidence.

5. requestAnimationFrame

RequestAnimationFrame understanding and practice

6. requestIdleCallback

The requestIdleCallback is something you should know about

7. DOMContentLoaded

7.1 what is

The DOMContentLoaded event is fired after the initial HTML document has been fully loaded and parsed, without waiting for the stylesheet, image, and subframe to be fully loaded.

Again, what does it mean that the HTML document is loaded and parsed? Or, what does the browser do before the HTML document is loaded and parsed? We need to talk about browser rendering.

The browser requests the HTML document from the server and parses it. The result is the DOM (Document Object Model), where the HTML document is loaded and parsed. If CSS exists, it generates a CSSOM (CSS object model) from THE CSS, and then the DOM and CSSOM are combined to create a render tree. Now that you have the render tree and know the styles of all the nodes, it’s time to calculate their exact size and position in the browser based on those nodes and styles. This is the layout phase. With this information, let’s draw the nodes to the browser. All the processes are shown below:

Now you probably have an idea of what the browser does before the HTML document is loaded and parsed, but that’s not the end of it, because we haven’t considered JavaScript, one of the main protagonists of today’s front end.

JavaScript can block DOM generation, that is, when the browser is parsing an HTML document, if encountered

<body>
  <script type="text/javascript">
  console.log(document.getElementById('ele')); // null
  </script>

  <div id="ele"></div>

  <script type="text/javascript">
  console.log(document.getElementById('ele')); // <div id="ele"></div>
  </script>
</body>
Copy the code

Also, because JavaScript can query the style of any object, it means that JavaScript can’t be executed until CSS parsing is complete, which is when CSSOM is generated.

At this point, we can summarize. When there is no script in the document, the browser parses the document and fires the DOMContentLoaded event. If a script is included in the document, the script blocks parsing of the document, and the script can’t be executed until the CSSOM build is complete. In any case, DOMContentLoaded triggers without waiting for other resources such as images to complete loading.

7.2 Asynchronous Scripts

So far we’ve been talking about the effect of synchronous scripting on page rendering, and if we want pages to display as quickly as possible, we can use asynchronous scripting. HTML5 defines two methods for defining asynchronous scripts: defer and async. Let’s take a look at the differences.

Synchronous scripts (without async or defer in the tag) :

If a script is encountered while the HTML document is being parsed, parsing is stopped, the script is loaded, then executed, and the HTML document is parsed. The process is shown as follows:

Defer script:

When the HTML document is parsed, if the defer script is encountered, it is loaded in the background without interruption. After the document is parsed, the defer script executes. Also, the order in which the defer scripts are executed depends on where they were defined. The process is shown as follows:

Async scripts:

When an HTML document is parsed, if an Async script is encountered, the script is loaded in the background, and the document parsing process is not interrupted. After the script is loaded, document parsing stops and the script is executed. After the script is executed, document parsing continues. The process is shown as follows:

If you Google “the difference between Async and defer” you’ll probably find a bunch of articles and images like the one above, but here I’d like to share with you how async and defer affect the DOMContentLoaded event trigger.

Defer to DOMContentLoaded

If defer is included in the Script tag, this part of the script will not affect the parsing of the HTML document, but will not be executed until the HTML parsing is complete. DOMContentLoaded will only be triggered after the script defer has finished executing. So what does that mean? The HTML document parsing is not affected. After the DOM build is complete, defer script execution, but before script execution, you need to wait for the CSSOM build to complete. After DOM and CSSOM are built and the defer script is executed, the DOMContentLoaded event fires.

Async and DOMContentLoaded

If async is included in the script tag, the HTML document build is unaffected and DOMContentLoaded fires after parsing, without waiting for the Async script to execute, the stylesheet to load, and so on.

7.3 DOMContentLoaded with the load

Looking back at the first picture:

Parallel to the blue line at marker 1, there is a red line that represents the time when the load event is triggered. Corresponding to this, in the bottom overview section, there is a red line “Load:1.60s” that describes the exact time when the Load event is triggered.

What’s the difference between these two events? Click on this page to see: testDrive-archive.azu…

DOMContentLoaded is triggered when the HTML document has been parsed, and the load event is triggered when all the resources have been loaded.

(document).ready(function()//… The code…). ; (document).ready(function() {//… The code… }); (document).ready(function()//… The code…). ; (document).load(function() {//… The code… }); Listen for the Load event.

7.4 the use of

document.addEventListener("DOMContentLoaded".function(event) {
      console.log("DOM fully loaded and parsed");
  });
Copy the code

7.5 compatibility

Green, rest assured use

8. MutationObserver

8.1 what is

MutationObserver is a built-in object that looks at DOM elements and triggers callbacks when changes are detected.

8.2 usage

Const targetNode = document.getelementById ('some-id'); // Observer configuration (what changes need to be observed) const config = {attributes: true, childList: true, subtree: true}; Const callback = function(mutationsList, const callback = function(mutationsList, const callback); observer) { // Use traditional 'for loops' for IE 11 for(let mutation of mutationsList) { if (mutation.type === 'childList') { console.log('A child node has been added or removed.'); } else if (mutation.type === 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.'); }}}; Const Observer = new MutationObserver(callback); Observe.observe (targetNode, config); // After that, you can stop observing observer.disconnect();Copy the code

8.3 the config

Config is an object with a Boolean option that says “what changes will be reacted to” :

  • childListnodeChanges to the immediate child node of,
  • subtreenodeChanges to all descendants of,
  • attributesnodeAttribute,
  • attributeFilter— An array of feature names, viewing only the selected feature.
  • characterData— Whether to observenode.data(Text content)

A few other options:

  • attributeOldValue– if fortrue, passes both the old and new values of the property to the callback (see below), otherwise just the new value (required)attributesOption),
  • characterDataOldValue– if fortrue, it willnode.dataBoth the old and new values are passed to the callback (see below), otherwise only the new value is passed (required)characterDataOption).

8.4 compatibility

9. Promise.any

9.1 what is

Promise.any() receives a Promise iterable and returns the Promise that succeeded as soon as one of the promises succeeds. If none of the promises in the iterable succeed (i.e. all Promises fail/reject), return an instance of the failed promise and AggregateError type, which is a subclass of Error and is used to group single errors together. Essentially, this method is the opposite of promise.all ().

9.2 Usage (Example)

const promise1 = new Promise((resolve, reject) => {
  setTimeout(reject, 100, 'promise 1 rejected');
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 400, 'promise 2 resolved at 400 ms');
});

const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 700, 'promise 3 resolved at 800 ms');
});

(async () => {
  try {
    let value = await Promise.any([promise1, promise2, promise3]);
    console.log(value);
  } catch (error) {
    console.log(error);
  }
})();
Copy the code

9.3 compatibility