Create by jsliang on 2019-2-23 20:55:34

Recently revised in 2019-3-12 21:34:59

Hello friends, if you think this article is good, remember to give astar, yourstarIs my motivation to learn!Making the address


Thanks to the refactoring of jsliang’s document library, some links to this article may not work, and Jsliang does not have the energy to maintain the old articles in Gold. Sorry. For those who want to get the latest posts, click on the GitHub address above and go to the document library to view the adjusted posts.


This article involves knowledge:

  • Shake and throttling
  • Redraw with reflux
  • Browser parses URL
  • DNS domain name Resolution
  • TCP Three handshakes and four waves
  • Browser render page

In this article, Jsliang will explain his personal understanding of the above points through his own explorations. If there are any flaws, omissions or misunderstandings, please leave your comments.

If your partner has questions about the article, you want to get a quick response. Or a friend who is interested in jsliang’s personal front end document library and wants to sort out their own front end knowledge. Welcome to add QQ group together to discuss: 798961601.

A directory

No toss of the front end, and salted fish what’s the difference

directory
A directory
The preface
Three tremble and throttling
 3.1 if you
 3.2 the throttle
Quadruple redraw with reflux
Browser parse URL
DNS domain name resolution
Seven TCP Three handshakes and four waves
Eight browser rendering pages
Nine summary
Chapter X References

The preface

Returns the directory

In our work, we may encounter problems like this:

  • When the user is searching, he is constantly knocking on the word. If we need to adjust the interface every time we knock on a word, the interface is called too frequently, and it gets stuck.
  • When the user is reading the article, we need to listen to which title the user is scrolling to, but every time we listen, it will be too frequent and occupy memory, if we add other business code, we will get stuck.

So, this is where we come in with shockproofing and throttling.

So, speaking of shaking and throttling, we can also explore the secret of redrawing and reflux.

Said lifting drawing and reflux, we will incidentally put the browser after the INPUT URL things also pay attention to, thus leads to DNS, TCP and other knowledge points, finally together constitute the outline of this article, convenient jsliang and small friends to this knowledge of the arrangement and memory.

Three tremble and throttling

Returns the directory

Getting to know something in code is often the fastest way to get to know something.

3.1 if you

Returns the directory

Below we have a small case code.

If you have a computer at hand and are interested in thinking about what stabilization is first. You can copy the code to the browser, try clicking the button, and take a look at the Console to see how it prints.

If you don’t have a computer at hand, let’s take a look at the code implementation and then watch the GIF demo below. (This effect is less effective than their own direct knock)

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Image stabilization</title>
</head>
<body>
  <button id="debounce">Shake me!</button>

  <script>
    window.onload = function() {
      // 1, get the button and bind the event
      var myDebounce = document.getElementById("debounce");
      myDebounce.addEventListener("click", debounce(sayDebounce));
    }

    // 2, anti - shaking function function, accept pass parameter
    function debounce(fn) {
      // 4, create a tag to store the return value of the timer
      let timeout = null;
      return function() {
        // 5, each time the user click/input, the previous timer is cleared
        clearTimeout(timeout);
        // 6, create a new setTimeout,
        // This ensures the interval between clicking the button
        // Fn will not be executed if the user also clicks
        timeout = setTimeout(() = > {
          fn.call(this.arguments);
        }, 1000);
      };
    }

    // 3. Event processing that requires shaking stabilization
    function sayDebounce() {
      / /... Some of the jobs that need to be stabilized are performed here
      console.log("Shake off success!");
    }

  </script>
</body>
</html>
Copy the code

Good, I’m sure you’ve read the code, so let’s see how it works:

At this point, we can throw out the concept of tremble:

  • Anti-shaking: If a task is triggered frequently, the task is executed only when the interval between triggering the task exceeds the specified interval.

Combining the above code, we can see that after triggering the click event, if the user clicks again, we will empty the previous timer and regenerate a timer. This is something that needs to wait, and if you keep pushing, I’ll start the clock again!

Talk is no use, show you

  • There’s an input box that calls the interface to get the associative word. However, because it’s not good to call the interface frequently, we use the stabilization function in the code so that the interface will be called and the associative words will appear only after a certain period of time after the user has finished typing.

Friends can try to look at the above case, first to achieve the solution of this scene, if you feel not, then see: “Tremble and throttling application Scenarios and Implementation”

What is arguments? First, you can think of Arguments as a tool that implements overloaded functions. Then, let’s take an example: In function test(), since we are not sure how many variables there are, such as test(“jsliang”, 24), or test(“LiangJunrong”, “jsliang”, “24”), All you need to do is accept arguments in function test. Finally, in function test() {let arr1 = argument[0]}, arr1 can get the first variable passed in. So, fn. Call (this, arguments) replaces the variable in the function.

Reference 1: Apply and Call in Casual JS Reference 2: Use arguments in JS

3.2 the throttle

Returns the directory

After shaking, let’s talk about throttling, rules do not say, first on the code:

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>The throttle</title>
</head>
<body>

  <button id="throttle">Cut me some slack!</button>

  <script>
    window.onload = function() {
      // 1, get the button, bind the click event
      var myThrottle = document.getElementById("throttle");
      myThrottle.addEventListener("click", throttle(sayThrottle));
    }

    // 2. Throttle function body
    function throttle(fn) {
      // 4. Save a tag with a closure
      let canRun = true;
      return function() {
        // 5, check whether the flag is true at the beginning of the function. If it is not true, interrupt the function
        if(! canRun) {return;
        }
        // 6. Set canRun to false to prevent it from being executed before it is executed
        canRun = false;
        // 7, timer
        setTimeout( () = > {
          fn.call(this.arguments);
          // 8. Set this flag to true after executing the event (i.e., calling the interface)
          canRun = true;
        }, 1000);
      };
    }

    // 3. Events that need throttling
    function sayThrottle() {
      console.log("Throttling success!");
    }

  </script>
</body>
</html>
Copy the code

Good, after looking at the code friends should have a general idea of what is going on, let’s look at the GIF implementation:

After looking at the code and the GIF implementation, we can see that throttling is:

  • Throttling: The task is executed only once in a specified interval.

So, throttling at work?

  1. Lazy load monitors the position of the computed scroll bar, which is obtained at a frequency of time using a throttle.
  2. The user clicks the submit button and, assuming we know the approximate return time of the interface, we use throttling to allow only one click in a certain amount of time.

In this way, in certain work scenarios, we can use damping and throttling to reduce unnecessary wastage.

The question is, if the interviewer hears you say this, will they follow up with, “Why is the above scenario so damaging?”

OK, here’s how the browser renders the page…

Quadruple redraw with reflux

Returns the directory

Before we talk about browser rendering, we need to understand two things. One is called browser parsing URL, and the other is redraw and reflux, which we’ll cover in this chapter:

  • Repaint: When the element style changes do not affect the layout, the browser will use repaint to update the element. In this case, only the UI level repaint is required, so there is less wastage.

Common redraw operations are:

  1. Changing the color of an element
  2. Change the element background color
  3. More……
  • Reflow: Also called layout. When an element’s size, structure, or certain properties are triggered, the browser rerenders the page, called reflux. At this point, the browser needs to be recalculated, and then the page layout needs to be re-calculated, so it is a heavy operation.

Common reflux operations are:

  1. Page first render
  2. Browser window size changed
  3. Element size/position/content changed
  4. Element font size changes
  5. Add or remove visible DOM elements
  6. Activate CSS pseudo-classes (:hover…)
  7. More……
  • Important: backflow must trigger redrawing, and redrawing does not necessarily trigger backflow. The cost of redrawing is small and the cost of backflow is high.

See here, friends may be a bit confused, you just told me about tremble and throttling, how suddenly jump to redraw and backflow?

OK, let’s take a look at the following scene:

  • There is a div box on the interface. Users can input some information about the div box in the input box, such as width and height, and change the properties immediately after input. However, since the changes are always stored in the database, the interface needs to be invoked. If left unchecked…

Why do you need to throttle? Some things cause browsers to backflow, and backflow causes browsers to cost more, so we use throttling to prevent these things from costing browsers more.

Let’s use a picture to illustrate:

In this way, we can visually combine shaking and throttling with redrawing and reflux.

So, how can we avoid heavy use of redraw and backflow at work? :

  1. Avoid frequent operation style, can be consolidated after a unified change
  2. Try to use classes for style changes rather than working with styles directly
  3. To reduce DOM operations, use string inserts once

OK, so now that we have covered two parts, the question arises again: “Is there a redraw and backflow in the browser rendering process?” “What happens between the time the browser enters the URL and the rendering succeeds?”

Let’s, uh, dig deeper…

Browser parse URL

Returns the directory

In order to make our level of knowledge seem deeper, we should consider the following two questions:

  • What happens between the time the browser enters the URL and the rendering is successful?
  • What happens during browser rendering, is there also a redraw and backflow?

OK, let’s start with the browser parsing the URL. Let’s look at what happens when the user enters the URL and the browser renders the page to the user:

  • A version of A:
  1. The user enters the URL.
  2. The DNS domain name is resolved for the URL.
  3. Establish a TCP connection (three-way handshake).
  4. The browser sends an HTTP request packet.
  5. The server returns an HTTP response packet.
  6. Close the TCP connection (four waves).
  7. The browser parses the document resources and renders the page.

At this point, I suddenly remembered a dialogue:

Student: “Teacher, what is the key point of this course?”

Teacher: “all is the key!”

enm… I don’t know if the teacher is going to get hit, but I do know if Jsliang is going to get hit by writing this, so let’s take a closer look at our structure with the above diagram:

Good, Jsliang feels like he’s taking his drawing skills a step further

I’m very grateful that there are so many articles on the Internet to refer to, but after looking through 20 or so articles, Jsliang felt that nine out of ten there were some questions in this section. I asked my friends, and some of them were right, and some were wrong. Still, keep reading. (2) To avoid problems, I’ll post another version below, and you can say which version you support in the comments section:

  • Version B
  1. The user enters the URL.
  2. The DNS domain name is resolved for the URL.
  3. TCP connection.
  4. Requests and responses are made to HTTP packets.
  5. The browser parses the document resources and renders the page.

Here we can see what happens from the user entering the URL to the browser presenting the page to the user.

Then the rest is simple:

  1. What is DNS resolution and how does it work?
  2. What is the TCP three-way handshake, what is the TCP four-way wave, and what is their process?
  3. What is the process by which the browser parses the document resources and renders the page?

Let’s go~ step by step to complete the following three knowledge!

Reference 1: “The whole process of Web Page parsing (input URL to display page)” Reference 2: “Browser Rendering Page Process Analysis”

DNS domain name resolution

Returns the directory

First, let’s solve the first problem:

  • What is DNS resolution and how does it work?

The Domain Name System (DNS) is an abbreviation for the Domain Name System. It is used to translate host names and Domain names into IP addresses:

Domain name: http://jsliang.top < – > DNS < – > IPV4:119.147.15.13

IPV4 is faked. It is used to indicate that the DNS can return an IP address after resolution

So, when the user enters http://jsliang.top in the browser, DNS goes through the following steps:

  1. The browser searches for the resolution records in the DNS (Domain name server) in the cache based on the address. If yes, the IP address is returned. If the domain name does not exist, the system checks whether the hosts file in the operating system has DNS resolution records of the domain name. If yes, the system returns the DNS resolution record.
  2. If the browser cache or the hosts file of the operating system in condition 1 does not have the DNS resolution record of the domain name, or the DNS resolution record has expired, the system sends a request to the DNS server to resolve the domain name.
  3. Request the local DNS server to resolve the domain name. If the DNS server fails to resolve the domain name, request the root DNS server to resolve the domain name.
  4. The root server returns a primary DNS server to the local DNS server.
  5. The local DNS server sends a resolution request to the primary DNS server.
  6. After receiving the resolution request, the primary DNS server searches for and returns the IP address of the DNS server corresponding to the domain name.
  7. The DNS server queries the stored mapping table between domain names and IP addresses and returns the destination IP address record and a Time To Live (TTL) value.
  8. The local DNS server receives the IP address and TTL values and caches them. The cache time is controlled by the TTL value.
  9. The domain name resolution result is returned to the user, and the user caches it in the local system cache according to the TTL value. The domain name resolution process is complete.

Text is always hard to understand, but follow jsliang’s drawing to make it clear:

Seven TCP Three handshakes and four waves

Returns the directory

Then, let’s solve the second problem:

  • What is the TCP three-way handshake, what is the TCP four-way wave, and what is their process?

What is TCP? Transmission Control Protocol (TCP) is a connection-oriented, reliable, and byte stream-based transport layer communication Protocol.

In simple terms, it is used to reliably transfer data streams from one host to another.

As for how it works, we can’t get into it right now. We just want to know two things: three handshakes and four waves.

  • Three handshakes:
  1. The first handshake: Both ends are CLOSED at first. The Client sets the SYN flag bit to 1 and generates a random valueseq = xAnd sends the packet to the Server. The Client enters the SYN-sent state and waits for the acknowledgement from the Server.
  2. Second handshake: indicates the flag bit when the Server receives the data packetSYN = 1When the Client requests to establish a connection, the Server sets both the SYN and ACK flags to 1.ack = x + 1, randomly generates a valueseq = y, and sends the packet to the Client to confirm the connection request, and the Server entersSYN-RCVDState, when the operating system allocates TCP cache and variables for the TCP connection.
  3. The third handshake: After receiving the confirmation, the Client checks whether the SEQ isx + 1, whether ACK is 1, if it is correct, set the flag bit ACK to 1,ack = y + 1At this time, the operating system allocates TCP cache and variables for the TCP connection and sends the packet to the Server. The Server checks whether the ACK isy + 1If the ACK is 1, the connection is established and the Client and Server enter the Established state. The three-way handshake is completed. Then the Client and Server can transmit data.

The text is too messy, show you picture:

  • Four waves:
  1. First wave: The application process of the Client first sends a connection to its TCP to release the segment (FIN = 1And the serial numberseq = u), and stop sending data again, actively close the TCP connection, enter the FIN-wait-1 state, and WAIT for the confirmation from the Server.
  2. Second wave: The Server sends an acknowledgement packet after receiving the connection release packet, (ACK = 1And confirm,ack = u + 1And the serial numberseq = v), the Server enters the close-wait state. At this time, TCP is in the semi-closed state, and the connection between the Client and the Server is released.

Note: After receiving the acknowledgement from the Server, the Client enters the FIN-wait-2 state and waits for the connection release packet segment sent by the Server.

  1. Third wave: The Server has no more data to send to the Client, the Server sends the connection release segment (FIN = 1.ACK = 1And the serial numberseq = wAnd confirm,ack = u + 1), the Server enters the last-ACK state and waits for the Client to confirm.
  2. The fourth wave: After receiving the connection release segment from the Server, the Client sends an acknowledgement segment (ACK = 1.seq = u + 1.ack = w + 1), the Client enters the time-wait state. The TCP is not released. The Client enters the CLOSED state only after the timer is set at 2MSL.

The text is too messy, show you picture:

OK, so we understand TCP and its process of three handshakes and four waves. To help you remember it, Jsliang has made a short story to help you remember it:

  • Three handshakes + four waves
  1. Jsliang :(initiates a wechat friend request to a girl) “hello, can I add you as a friend?” — The first handshake
  2. Girl :(approved) “hello, nice to meet you” — second handshake
  3. Jsliang: “Hello, my name is Liang Junrong, front end toss little expert…” — The third handshake
  4. … (Chat content)
  5. ………………… (Chat content)
  6. ……………………… (Chat content)
  7. ………………… (Chat content)
  8. … (Chat content)
  9. Jsliang :(cold takes a picture of a paper basket full of paper towels) “oh, I feel so bad today.” — First wave
  10. Sister: “god, you are disgusting!” — Second wave
  11. Sister: “za or when not know, each other deleted, thank you!” — Third wave
  12. Jsliang :(dumb) “no, you listen to me!” — The fourth wave
  13. Girl :(unfriend) — CLOSED
  14. Jsliang: (! “I have a cold today.” Girl has friend verification on, and you’re not her friend yet. Please send a friend verification request first. After the authentication is passed, the chat can be started. – CLOSED

OK, successful humiliate, believe small partners have a very good understanding.

So, let’s move on and explore.

Ref. 1: TCP Three-way Handshake and Four-way Wave Process ref. 2: TCP Three-way Handshake and Four-way Wave Process

Eight browser rendering pages

Returns the directory

Finally, let’s tackle the third problem:

  • What is the process by which the browser parses the document resources and renders the page?

Without further ado, let’s take a look:

  1. HTMLParser is used by browsers to parse HTML into DOM trees based on the principle of depth traversal.
  2. The browser parses the CSS into a CSS Rule Tree (CSSOM Tree) through CSSParser.
  3. The browser uses JavaScript to parse JS code through either the DOM API or the CSSOM API and applies it to the layout, rendering the response as required.
  4. The Render Tree is constructed from the DOM Tree and the CSSOM Tree.
  5. When the geometry of any of the nodes in the Render tree changes, the render tree rearranges and recalculates the positions of all the nodes on the screen.
  6. Repaint: Render tree repaints when any of the element’s style attributes (geometric size unchanged) change, such as font color, background, etc.
  7. Paint: Traverse the Render tree and invoke the hardware graphics API to draw each node.

The text is definitely not clear enough, but Jsliang was tired after drawing a few pictures, so we stole one:

In this way, we know how the browser renders the page

Reference: “One Essay To Nail the Front End Interview”

Nine summary

Returns the directory

So what do we do now?

  1. We had some problems at work that were causing pages to get stuck, so we looked it up and knew that to reduce browser overhead, we needed to use shockproof and throttling.
  2. Having solved the problem with shaking and throttling, we wondered why this was happening, so we took a closer look at redrawing and backflow.
  3. Redraw and backflow only tell us how the browser renders the CSS. We need to learn more about the details of how the browser renders the page, but the onion has to be peered off one layer at a time, so we need to start with the browser parsing the URL.
  4. In browser parsing URL, we also know DNS domain name resolution, TCP three handshake and four wave these two knowledge points.
  5. Finally, we know how browsers render pages.

To sum up, if we only need to focus on one point in the interview, we are likely to be asked a lot of questions because we don’t know the beginning and end of the interview.

However, if we know a knowledge point, and its ideas diverge, in-depth study, I believe that when the interviewer asks, friends can talk freely, and will not be asked to the whole body!

Finally, I wish you can find a suitable and satisfactory job

Chapter X References

Returns the directory

  1. Function stabilization and Throttling
  2. Throttling & Anti-Shaking
  3. “JS Magic trick: Tremble function and throttling function”
  4. Apply and Call in Casual JS
  5. How to Use Arguments in JS
  6. “Application Scenarios and Implementation of damping and Throttling”
  7. “The whole process of Web page parsing (input URL to display page)”
  8. Browser Page Rendering Process Analysis
  9. “One Essay to Nail the Front End Interview”



Jsliang’s document library 由 Liang JunrongusingCreative Commons Attribution – Non-commercial – Share in the same way 4.0 International licenseLicense.

Based on theGithub.com/LiangJunron…On the creation of works.

Permissions outside of this license agreement may be obtained from
Creativecommons.org/licenses/by…Obtained.