Summary of front-end interview questions (theory part 1)--page loading and request, network

The whole process from inputting URL to page rendering

1) Enter the URL

2) Check the cache

3) DNS domain name resolution to obtain the IP address

4) The browser establishes a connection with the server (TCP three-way handshake)

4) Send an HTTP request to the server, and the server returns a response

5) The browser parses the response and renders the page

6) Disconnect (four waves)

Page rendering and page loading order of resources

1) The loading order of a page is sequentially loaded from top to bottom, and loading and rendering are performed simultaneously.

2) When referencing an external js file, when a <script> tag is encountered during loading, the browser will send a request to the server and wait for the request to return.

Because the browser needs a stable DOM tree structure, and it is very likely that there is code in JS that directly changes the DOM tree structure, such as using document.write or appendChild, or even directly using location.href to jump. To prevent JS from modifying the DOM tree, the DOM tree needs to be rebuilt, so loading js will block the download and presentation of subsequent content.

3) When using embedded js, it will block the rendering of all content.

4) When the <style> tag is encountered during the loading process, the browser will send a request to request CSS or image, and then continue to perform the following conversion without waiting for the return of the request. When the request returns, only need It is OK to put the returned content into the corresponding position in the DOM tree, so normally CSS will not block the page (it will not block the parsing of the DOM, but will block the rendering of the Dom ).

But there are exceptions: when CSS is followed by embedded JS, the CSS will block the download of subsequent resources.

Reason: Because the browser will maintain the order of css and js in html, the style sheet must be loaded and parsed before the embedded JS is executed. The embedded JS will block the subsequent resource loading, so the above CSS blocking download will appear.

The browser loads the page rendering process:

The browser rendering process is as follows:

1. The rendering engine first obtains the content of the requested document through the network

2. Parse the HTML file to generate a DOM Tree

3. Parse the CSS file to generate CSSOM (CSS Object Model)

4. Integrate DOM Tree and CSSOM to generate Render Tree (render tree)

5. According to Render Tree rendering and drawing, render pixels to the screen.

6.layout layout (rearrangement in this step, determine the size and position, etc., can be imagined as cutting the page into pieces)

7. Render each node (redrawing is at this step, which is why rearrangement must be redrawn, and redrawing is not necessarily rearrangement)

Why does js block browser rendering?

Because when the browser is building the DOM tree, if it encounters js, it will interrupt the construction of the DOM tree, hand over the control to the js engine, and continue to build the DOM tree after the execution of js is completed.

Why does css block browser rendering?

1) CSS will block the rendering tree generation. If it is not blocked, when the css is loaded, it will be redrawn or reflowed, causing unnecessary performance consumption.

2) css will not directly block the construction of the DOM tree, but will block the execution of js, and js will block the construction of the DOM tree, so css will indirectly block the construction of the DOM tree.

Why does css block js execution?

Because js needs to read and modify the node style through CSSOM, it will wait for the CSSOM architecture before executing it.

Key summary:

  • DOM parsing and CSS parsing are two parallel processes, so this also explains why CSS loading does not block DOM parsing.
  • However, since Render Tree is dependent on DOM Tree and CSSOM Tree, it must wait until CSSOM Tree is built, that is, CSS resource loading is complete (or CSS resource loading fails), before rendering can begin. Therefore, CSS loading will block the rendering of Dom.
  • Since js may manipulate previous Dom nodes and css styles, the browser will maintain the order of css and js in html. Therefore, the style sheet will be loaded and executed before the subsequent js is executed. So css will block the execution of subsequent js.

What is the function and difference of script tag async and defer attributes?

Function: The loading of the script will not block the browser rendering

the difference:

1) defer is HTML4 standard, async is HTML5 standard

2) defer is loaded and executed according to the order of the document, and async means that the script is loaded first and executed first

3) defer is executed after the DOM tree is constructed, and async is executed without waiting for the DOM tree to be constructed

Reflow and repaint

A rearrangement occurs:

1) Initial rendering of the page

2) Add/remove visible DOM elements

3) Change the element position

4) Change element size (width, height, inner and outer margins, borders, etc.)

5) Change element content (text or picture, etc.)

6) Change the window size

A repaint occurs:outline , visibility, color,background-color等

How to reduce rearrangement and redrawing

Since reflow and redrawing will bring a lot of performance overhead, we should try to avoid or reduce the number of reflow and redrawing in development to improve performance

1. Avoid frequently reading properties that will cause reflow/redrawing. If you really need to use it multiple times, use a variable to cache it.

2. Use absolute positioning for elements with complex animations to keep them out of the document flow, otherwise it will cause frequent reflow of parent elements and subsequent elements.

3. To avoid frequently manipulating the DOM, you can create a documentFragment, complete all DOM operations, and finally add it to the document.

4. To avoid frequent manipulation of styles, it is best to rewrite the style attribute at one time, or define the style list as a class and change the class attribute at one time.

What are base types and reference types? Which ones are on the stack? Which ones are in the pile?

Basic types : basic data types are simple data segments stored on the stack (comparisons are comparisons of values)

String  Number  Boolean  undefined   null  symbol

Reference type : The reference data type is an object stored in the heap memory. The reference address of the specific content in the heap memory is stored in the stack memory. Through this address, the object can be quickly found (the comparison is a comparison of references)

Array Object   Function  Date

When a variable assigns a value of reference type to another variable, the value in the stack memory is also copied and placed in the space allocated by the new variable, but the variable of the reference type stored in the stack memory is an address, this The address points to the object in the heap memory, so this variable actually copies an address, and the two addresses point to the same object, and changing any of the variables will affect each other.

The address stored in the stack memory points to the object in the heap memory

Basic data types and reference types in JavaScript_js primitive data types and reference data types_Xiaohanhan dare not. Blog-CSDN Blog

Why is js single-threaded?

JavaScript's single thread is related to its use. The main purpose of JavaScript is to interact with users and manipulate DOM, which determines that it can only be single-threaded, otherwise it will bring very complicated synchronization problems. For example, assuming that JavaScript has two threads at the same time, one thread adds content to a certain DOM node, and the other thread deletes this node, which thread should the browser take as the basis?

js solves single-thread blocking problem

        Single thread means that all tasks need to be queued, and the next task will be executed only after the previous task is completed. If the previous task takes a long time, the latter task will have to wait forever. If the queuing is due to a large amount of calculations and the CPU is too busy, forget it, but most of the time the CPU is idle, because the IO device (input and output device) is very slow (such as Ajax operations read data from the network), you have to Wait for the result to come out before proceeding.

        The designers of the JavaScript language realized that at this time, the main thread can completely ignore the IO device, suspend the waiting tasks, and run the tasks that are queued first. Wait until the IO device returns the result, then go back and continue the execution of the suspended task.

        Therefore, all tasks can be divided into two types, one is synchronous tasks (synchronous), and the other is asynchronous tasks (asynchronous). A synchronous task refers to a task that is queued for execution on the main thread, and the next task can only be executed after the previous task is executed; an asynchronous task refers to a task that does not enter the main thread but enters the "task queue" (task queue) Task, only when the "task queue" notifies the main thread that an asynchronous task can be executed, the task will enter the main thread for execution.

Event loop EventLoop

Synchronous and asynchronous tasks enter different execution environments, synchronously enter the main thread, that is, the main execution stack, and asynchronously enter the task queue (Event Queue, the mechanism is first-in-first-out). The task in the main thread is empty after execution, it will go to the task queue to read the corresponding task, and push it to the main thread for execution. The continuous repetition of the above process is what we call Event Loop (event loop).

(When executing JS, when a synchronous task is encountered, it is directly pushed into the call stack for execution. When an asynchronous task is encountered, the task is suspended. After the asynchronous task returns, it is pushed into the task queue. After all tasks in the call stack are executed, Push and execute the task queue one by one, repeating this series of behaviors is called event loop)

Synchronous task (synchronous)

Also known as non-time-consuming tasks, they refer to those tasks that are queued for execution on the main thread

The next task can only be executed after the previous task is completed

②Asynchronous task (asynchronous)

Also known as time-consuming tasks, asynchronous tasks are entrusted by JavaScript to the host environment for execution

When the execution of the asynchronous task is completed, the JavaScript main thread will be notified to execute the callback function of the asynchronous task
 

Synchronous task : A task queued for execution on the main thread. Only when the previous task is completed can the next task be executed.

Asynchronous tasks : tasks that do not enter the main thread but enter the "task queue", only after the main thread tasks are all executed , the tasks in the "task queue" will enter the main thread for execution

  1. Macro task: setInterval() setTimeout() setImmediate() ajax event binding

  2. Micro task: then and catch function after new Promise(), new MutationObserver, process.nextTick

process.nextTick() and Promise callback, who will be executed first

process.nextTick(function(){

    console.log(7);

});

new Promise(function(resolve){

    console.log(3);

    resolve();

    console.log(4);

}).then(function(){

    console.log(5);

});

process.nextTick(function(){

    console.log(8);

});

//这段代码运行结果是3,4,7,8,5

process.nextTick()It is a method in the Node environment, so we talk about it based on Node.

process.nextTick()It is a special asynchronous API that does not belong to any Event Loop phase. In fact, when Node encounters this API, the Event Loop will not continue at all, it will stop executing immediately process.nextTick(), and the Event Loop will continue after the execution is completed.

Cross-domain problem solution

  • JSONP : The principle of jsonp is to use the script tag to not be restricted by the browser's same-origin policy, and then cooperate with the backend to solve cross-domain problems.
  • CORS : cors is cross-domain resource sharing. It is a mechanism based on HTTP headers. By allowing the server to mark other origins (domains, protocols and ports) other than itself, the browser allows these origins to access and load their own resources. . CORS is enabled when Access-Control-Allow-Origin is set on the server side, so as long as the backend implements CORS in this way, the cross-domain problem can be solved, and the frontend does not need to be configured.
  • Build a Node proxy server to solve cross-domain: Because the same-origin policy is restricted by the browser, the server request server is not restricted by the same-origin policy of the browser, so we can build our own node server to proxy access to the server.

    The general process is : we request our own node proxy server on the client side, and then forward the client's request to access the server in the node proxy server. returned to the client. There are also cross-domain problems between the client and the proxy server built by itself, so CORS needs to be set in the proxy server.

  • Nginx reverse proxy solves cross-domain : nginx solves cross-domain through reverse proxy, which is also realized by using the server to request the server not to be restricted by the browser's same-origin policy.

  • The window.postMessage()  method can safely implement cross-origin communication. This method is a controlled mechanism to circumvent this limitation. As long as it is used correctly, this method is very safe.

    The main purpose is to realize multi-window, multi-document communication:

  1. Data transfer for pages and new windows they open
  2. Message passing between multiple windows
  3. Pages with nested iframe messaging

Summary:
The principle of jsonp is that the script tag is not restricted by the same-origin policy of the browser, and the img and link tags are not restricted by the same-origin policy of the browser.
Cross-domain is a browser restriction, and communication between servers is not restricted by the same-origin policy of the browser.
All cross-domain solutions require the cooperation of the server.
The most commonly used cross-domain solutions are CORS, Node proxy server and Nginx reverse proxy.
postMessage is more used to send data between multiple documents and windows.
 

When does cross domain appear

Different source policies will cause cross-domain problems

First, the URL consists of three parts: protocol domain name port

When any one of the protocol, domain name, and port of a request URL is different from the current URL, it is cross-domain

The difference between v-if and v-show

1) v-if is to dynamically add or delete DOM elements to the DOM tree

     v-show is to set the display attribute of the DOM element to control the display and hide

2) v-if switching has a process of partial compilation and uninstallation, and the switching process properly destroys and rebuilds internal event listeners and subcomponents.

     v-show is just simple css toggle

3) v-if has higher switching consumption; v-show has higher initial rendering consumption

4) v-if is lazy, the initial condition is false do nothing, only the condition becomes true for the first time partial compilation

    v-show is compiled in any condition, and is then cached and retained by DOM elements

5) v-if suitable for operating conditions unlikely to change

    v-show is suitable for frequent switching

bind,apply,call

 1) When fn.call is called, the this point in fn will be modified to the first parameter passed in thisArg; the following parameters will be passed to fn, and the function fn will be executed immediately.

fn.call(thisArg, arg1, arg2, arg3, ...)

2) The function of fn.apply is the same as call: modify the point of this and execute fn immediately. The difference is that the form of parameter passing is different. apply accepts two parameters. The first parameter is the this object to point to, and the second parameter is an array. The elements in the array will be expanded and passed to fn as the parameter of fn. 

 apply(thisArg, [argsArr])

3) The function of fn.bind is to only modify the this point, but not execute fn immediately; it will return a fn after modifying the this point. Need to be called to execute: bind(thisArg, arg1, arg2, arg3, ...)(). The parameter passing of bind is the same as that of call. 

bind(thisArg, arg1, arg2, arg3, ...)

1. The same point
The three are used to change the direction of this;
the first parameter received is the object to be pointed to by this;
all of them can use subsequent parameters to pass parameters.
2. The difference is that
call and bind pass the same parameters, and multiple parameters are passed in one by one;
apply only has two parameters, and the second parameter is an array; both
call and apply directly call the function, and the bind method will not be called immediately function, but returns a function that modifies this

talk about websocket

webscoket is a network communication protocol, because http has flaws, the communication can only be sent by the client, and the server cannot actively send messages to the client. Because websocket has full-duplex communication, it can realize communication between multi-tab pages.

Webscoket life cycle and heartbeat mechanism - Holly31's Blog - CSDN Blog

HTTP request

HTTP request refers to the request message from the client to the server

HTTP is the Hypertext Transfer Protocol, which defines the text transmission specification between the client and the server

HTTP request includes: protocol, request method, request header, request body

1) Request method: get, post, put, delete, options, head, connect

2) URL address

3) Protocol name and version number

4) HTTP message header

5) Message body

The difference between get and post

  •  1. Get is used to obtain data from the server, and Post is used to transfer data to the server.
  •  2. Get adds the data in the form to the URL pointed to by the action in the form of variable=value, and uses "?" to connect the two, and uses "&" to connect each variable; Post uses the form's The data is placed in the data body of the form, and is passed to the URL pointed to by the action according to the way the variables correspond to the values.
  •  3. Get is not safe, because during the transmission process, the data is placed in the URL of the request, and many existing servers, proxy servers or user agents will record the request URL in a log file, and then put it in a certain In this way, some private information may be seen by third parties. In addition, the user can also directly see the submitted data on the browser, and some internal system information will be displayed in front of the user. All Post operations are invisible to the user.
  •  4. The amount of data transmitted by Get is small, which is mainly due to the limitation of the URL length; while Post can transmit a large amount of data, so you can only use Post when uploading files (of course there is another reason, which will be mentioned later).
  •  5. Get restricts the value of the data set of the Form form to be ASCII characters; while Post supports the entire ISO10646 character set.
  •  6. Get is the default method of Form.

The data transmitted by Post can be converted into Chinese correctly by setting the encoding; while the data transmitted by Get has not changed. In future programs, we must pay attention to this point.

HTTP Methods: GET vs. POST | Tutorial

HTTP cache

When a browser visits a website, if it is the first visit, it needs to load various resources (html js css img, etc.), and when we visit again later, it does not need to be obtained from the server again, but can be obtained directly from the cache to improve the access speed of the website .

The simple process of client requesting resources:

1) When requesting for the first time, the server returns the resource, and indicates the cache parameters in the response header, and the client caches the resource.
2) When requesting again, it will first access the browser cache. If it hits the strong cache, the resource will be directly extracted, and the status code will return 200
3) If the strong cache is missed, send the request to the server to determine whether the local negotiation cache is invalid, and return 304 if it is valid. 4
) If the negotiation cache is not hit, the server returns the complete resource and updates the cache

Mandatory caching : set cache-control: max-age= (in seconds) in the response header. (cache-control: no-cache does not cache) The browser saves the file in the local cache. The next time the resource file is requested, check whether the max-age expires

Negotiation cache : When the browser visits the website, the server returns the resource and the resource identifier, and the browser can save the resource and the resource identifier in the browser. When the website is accessed again, the browser sends the request and the resource identifier to the server, and the server uses the resource identifier Determine whether the current version is consistent with the server version, return 304 if consistent, the browser directly fetches the file from the cache, return 200 if inconsistent, and return the new resource and resource ID at the same time, the browser is caching.

The difference between page cache (browser cache) cookie, localStorage and sessionStorage

1. The validity period of the stored time is different

    1) The validity period of the cookie can be set. By default, it expires after closing the browser.

    2) The validity period of sessionStorage is only kept on the current page, and it will become invalid after closing the current session page or browser

    3) The validity period of localStorage is always valid without manual deletion

2. The size of the storage is different

     1) The cookie storage is about 4kb, and the storage capacity is relatively small. Generally, a page can store up to 20 pieces of information

     2) The storage capacity of localStorage and sessionStorage is 5Mb (official introduction, there may be some differences with browsers)

3. Communication with the server

   1) The cookie will participate in the communication with the server, and is generally carried in the header of the http request, such as some key key verification, etc.

   2) localStorage and sessionStorage are pure front-end storage and do not participate in communication with the server

4. Convenience of reading and writing operations

   1) Cookie related operations, cookie operation is more cumbersome, and some data cannot be read and operated

//JavaScript 中,创建 cookie 如下所示:
document.cookie="username=John Doe";
//您还可以为 cookie 添加一个过期时间(以 UTC 或 GMT 时间)。默认情况下,cookie 在浏览器关闭时删除:
document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT";
//您可以使用 path 参数告诉浏览器 cookie 的路径。默认情况下,cookie 属于当前页面。
document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/";
//cookie的读取
var x = document.cookie;

2) Related operations of sessionStorage

//存储一条数据
sessionStorage.setItem('数据名', '数据值');
//读取一条数据
let data = sessionStorage.getItem('数据名');
//清除一条数据
sessionStorage.removeItem('数据名');
//移除所有数据
sessionStorage.clear();

3) Related operations of localStorage

//存储一条数据
localStorage.setItem('数据名', '数据值');
//读取一条数据
let data = localStorage.getItem('数据名');
//清除一条数据
localStorage.removeItem('数据名');
//移除所有数据
localStorage.clear();

5. Support for browsers

1. Cookies appeared earlier, and all browsers currently seen support them.

2. localStorage and sessionStorage appear late, and do not support browsers with lower versions (for example, versions below IE8 do not support them)

The difference between cookie and session

①Cookie can be stored in the browser or locally, and Session can only exist in the server
②Session can store any java object, and cookie can only store objects of type
String You can attack after your cookie)
④Session takes up server performance, too many sessions, increasing server pressure
⑤The data saved by a single cookie cannot exceed 4K, many browsers limit a site to save up to 20 cookies, Session has no size limit and server related to the memory size.


        Session is another mechanism for recording client status. The difference is that Cookie is saved in the client browser, while Session is saved on the server. When the client browser accesses the server, the server records the client information on the server in some form. This is Session. When the client browser visits again, it only needs to find the status of the client from the Session.

The combination of cookies and sessions has been used in
web development so far, and some very mature solutions have emerged for the use of cookies and sessions. In today's market or enterprise, there are generally two storage methods:

1. Stored on the server side: store a session_id through a cookie, and then save the specific data in the session. If the user has already logged in, the server will save a session_id in the cookie, and the next time the request is made again, the session_id will be brought up, and the server will obtain the user's session data in the session library according to the session_id. You can know who the user is and some status information saved before. This technical term is called server side session.
2. Encrypt the session data and store it in the cookie. This technical term is called client side session. Flask uses this method, but it can also be replaced by other forms.

Three-way handshake principle:

The first handshake: the client sends a packet with the SYN (synchronize) flag to the server;

The second handshake: After the server receives it successfully, it returns a packet with the SYN/ACK flag to deliver confirmation information, indicating that I have received it;

The third handshake: the client sends back a data packet with the ACK flag, indicating that I know, and the handshake ends.

waved four times 

The first wave : the client sends a FIN to close the data transmission from the client to the server, and the client enters the FIN_WAIT_1 state;

The second wave : After receiving the FIN, the server sends an ACK to the client, confirming that the sequence number is the received sequence number + 1 (same as SYN, one FIN occupies one sequence number), and the server enters the CLOSE_WAIT state;

The third wave : the server sends a FIN to close the data transmission from the server to the client, and the server enters the LAST_ACK state;

The fourth wave : After the client receives the FIN, the client t enters the TIME_WAIT state, and then sends an ACK to the server, confirming that the serial number is the received serial number + 1, and the server enters the CLOSED state, and completes four waved hands.
 

Guess you like

Origin blog.csdn.net/Holly31/article/details/130740762