Asynchronous loading of JS files

Why load JS files asynchronously? Because loading js blocks browser rendering.

The first solution is to write the js file under the body

The second solution is async. The browser will start a thread to download THE JS file and render the HTML at the same time. However, as soon as the JS file is loaded, it will execute the JS file, so it may block.

The third solution is to use defer, which is similar to Async, but defer, which waits for the HTML rendering to complete before executing the JS file after loading the JS.

Array to heavy

The first type: ES6 Set

function unique (arr) {
  returnArray.from(new Set(arr))} var arr = [1,1,'true'.'true'.true.true, 15, 15,false.false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a'.'a', {}, {}]; Console. log(unique(arr)) //set= new Set([1, 2, 3, 4, 4]); Set [...] / [1, 2, 3, 4] / / two cases of const items = new set ([1, 2, 3, 4, 5, 5, 5, 5)); items.size // 5Copy the code

The second is a double-layer for loop that uses splice to delete the same.

function unique(arr){            
        for(var i=0; i<arr.length; i++){
            for(var j=i+1; j<arr.length; j++){
                if(arr[I]==arr[j]){// if arr[I]==arr[j]); j--; }}}return arr;
}Copy the code

IndexOf retrieves the presence of a character in the array and returns -1 if it is not present. If it does, it returns the subscript. Includeds do the same thing

   function unique(arr) {    if(! Array.isArray(arr)) { console.log('type error! ')        return    }    var array = [];    for (var i = 0; i < arr.length; i++) {        if (array.indexOf(arr[i]) === -1) {            array.push(arr[i])        }    }    returnarray; }function unique(arr) {
    if(! Array.isArray(arr)) { console.log('type error! ')
        return
    }
    var array =[];
    for(var i = 0; i < arr.length; i++) {
            if(! Array.push (arr[I]); array.push(arr[I]); }}return array
}Copy the code

Use sort to sort the array and then make sure that the comparisons on the left and right are the same.

function unique(arr) {
    if(! Array.isArray(arr)) { console.log('type error! ')
        return;
    }
    arr = arr.sort()
    var arrry= [arr[0]];
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] !== arr[i-1]) {
            arrry.push(arr[i]);
        }
    }
    return arrry;
}Copy the code

How to determine the object type

Typeof x == ‘string’ typeof(x);

Var d = new String(‘test’); d instanceof String ==true;

The Object types in the Object. The prototype. ToString. Call ();

Js front-end event stream

What is the JS event flow? Do you know what an event delegate is?

Events are generally triggered in three stages:

1. The window propagates to the event trigger, which is triggered when a registered capture event is encountered

2. When propagated to the event trigger, the registered event is triggered

3. Propagates from the event trigger to the window, which is triggered when a registered bubbling event is encountered

So when a LI is bound to a click event, we click on the li, and we go from window=> to div to =>ul=> to Li, all the way down to Li, and if there’s a registration event in the middle of it like there’s a click event on ul, it’s going to fire as well. This is the capture event. When caught at the event trigger, we step back, bubbling outward once. This process is called bubbling.

The third argument to the addEventListener used to register events is a Boolean value. It controls whether the bubbling and capture events are executed. When the third parameter is set to true it is executed during capture, otherwise it is executed during bubbling. Both false, which means the bubble status is higher by default, and both true, which goes in order, capturing first.

<body>  <div id="app">    <div id="wrapper">      123    </div>  </div>  <script>    var node = document.getElementById('app') // The third addEventListener parameter? node.addEventListener('click'.function(event) {        console.log('app');      },      false// invalidate capture by defaultfalse    )    var Wrapper = document.getElementById('app') // The third addEventListener parameter? Wrapper.addEventListener('click'.function(event) {event. StopImmediatePropagation () / / stop all / / the event stopPropagation () / / stop the bubbling console. The log ('wrapper');        },        true) // At the same timefalse, is the default bubble status is higher, while fortrue</script> </script>Copy the code

Event delegation

<body>    <ul id="ul">        <li>1</li>        <li>2</li>        <li>3</li>        <li>4</li>        <li>5</li>    </ul>    <script>        let ul = document.querySelector('#ul')        ul.addEventListener('click'.function(event) {            console.log(event.target.innerText);        })    </script></body>Copy the code

The bubbling mechanism was used to make event delegation, and the click event of Li was entrusted to UL.

Event delegation means that instead of setting listeners on the event (direct DOM), listeners are set on its parent element. With event bubbling, the parent element can listen for events on the child element and respond differently by determining the type of the DOM element on which the event occurred.

Image preloading and lazy loading

Lazy loading:

1. Use setTimeout to control the loading of pictures. We load the pictures of the visible area first and then use a timer to load the rest of the pictures.

2. Monitor scrolling, we only load the visual area first, and then monitor the scrolling length of the screen to load pictures that need to be loaded.

3. Conditional loading, where certain conditions such as clicking on something are being loaded.

Preloading: Images are preloaded into the local cache and rendered directly from the local cache when needed.

Method 1: Preload with CSS and JavaScript

In the first step, we get the element that uses the class selector and set the background property to it to preload different images. In the second step, we use the addLoadEvent() function to delay the loading time of the preloader() function until the page is loaded. Method 2: Use JavaScript only for preloading Method 3: Use Ajax for preloading

A comparison of the two;

Both are used to optimize page loading images, but the principle is the opposite, lazy loading is lazy loading, preloading is early loading.

shift splice slice pop

The splice() method adds/removes items from/to the array and returns the deleted items. (This method changes the original array)

The pop() method removes and returns the last element of the array. This method deletes the last element of the arrayObject, reduces the array length by one, and returns the value of the element it deleted. If the array is already empty, pop() does not change the array and returns undefined.

The slice() method returns selected elements from an existing array. (This method does not change the original array)

The shift() method removes the first element from an array and returns the value of the first element. If the array is empty, the shift() method does nothing and returns undefined. Note that this method does not create a new array, but modifies the existing arrayObject directly.

Semantic HTML

Do the right thing with the right label.

Advantages:

  • Structure your page content.
  • Easy for browser parsing and SEO optimization.
  • Improve code maintainability and reusability

The difference between function declarations and function expressions

1. Function declarations promote the whole function, and the function expression will also promote, but only the expression name. (Promotion of functions is superior to promotion of variables.)

2. Function declarations can be executed before function declarations, and function expressions after function declarations

Functions defined as function declarations are not really declarations. They can only appear globally or nested within other functions, but they cannot appear in loops, conditions, or try/catch/finally. Function expressions can be declared anywhere. In other words, a function declaration is not a complete statement and therefore cannot appear in if-else,for loops, finally, try catch statements, and with statements.