preface

Hello, I’m Lin Sanxin. I’m sure you’ve been asked many times in interviews, “Tell me about what happens when you enter a URL into the URL bar.” I believe that many people can recite all the steps, but only will not be able to recite, in fact, this question contains a lot of browser and performance optimization knowledge points, today I will share with you these 15 knowledge points

What happens when you type in the URL?

  • 1. Enter the URL in the address box of the browser and press Enter.
  • 2. The browser checks whether the current URL is cached and compares whether the cache is expired.
  • 3. The DNS resolves the IP address corresponding to the URL.
  • 4. Establish a TCP connection based on the IP address (three-way handshake).
  • 5. HTTP initiates the request.
  • 6. The server processes the request and the browser receives the HTTP response.
  • Render the page and build the DOM tree.
  • 8. Close the TCP connection (four waves).

Eternal diamond

1. What should a browser do?

  • 1. Network: The browser downloads various resources through the network module, for exampleHTML text, JavaScript code, CSS style sheets, images, audio and video files, etc. The network part is particularly important because it takes time and requires secure access to resources on the Internet
  • 2. Resource management: Resources downloaded from the network or obtained locally need to be availableEfficient mechanismTo manage them. Such as how toAvoid duplicate downloads, how to cache resources and so on
  • Web browsing: This is the core of the browser and the mostbasicThe function of the mostimportantThe function. This feature determines how theResources are transformed into visualizationsThe results of the
  • 4. Multi-page management
  • 5. Plug-in and management
  • 6. Accounts and synchronization
  • 7. Security mechanism
  • Developer tools

The main function of the browser can be summed up in one sentence: turn the URL entered by the user into a visual image.

2. The browser kernel

The most important module in the browser is to turn all requested resources into visual images. This module is the browser kernel, which is also known as the rendering engine.

Here’s a summary of the browser kernel:

  • 1, IE:Trident
  • 2, Safari:WebKit. WebKit itself is mainly composed of two small engines, one is the rendering engine “WebCore”, the other is the javascript interpretation engine “JSCore”, they are derived from KDE’s rendering engine KHTML and javascript interpretation engine KJS.
  • 3, Chrome:Blink. Starting with Chrome 28.0.1469.0 in 2013, Chrome abandoned the Chromium engine and switched to the latest Blink engine (based on WebKit2 — apple’s new WebKit engine released in 2010). Blink has streamlined code, improved DOM framework, and improved security over previous generation engines.
  • 4. Opera: Abandoned in February 2013Presto, the use ofChromiumEngine, turn againBlinkengine
  • 5, Firefox:Gecko

3. Processes and threads

  • 1, process: a program execution, it occupies a unique memory space, isThe operating systemperformThe basic unit
  • 2. Thread: an independent unit of execution within a process. It is the minimum unit of CPU scheduling.The program runstheThe basic unit
  • 3, a processAt least,There is a running thread:The main thread. It is created automatically after the process starts
  • A process can run multiple threads at the same time, we often say that the program isMultithreaded operationFor example, you useListening to music softwareThis software is one of themprocessAnd you’re in the softwareListening to music.Collection of songs.Thumb up commentsThis is a processMultiple thread operation
  • 5. Data in a process can be available to multiple threads within itDirect sharing, butProcesses and processesBetween the dataCan't sharethe
  • 6. The JS engine isSingle threaded runthe

4. The main module of the browser rendering engine

  • 1. HTML parser: interpretAn HTML documentThe main function of the parser isInterprets HTML text as a DOM tree
  • 2. CSS parser: This is an object for each element in the DOMCalculate the style informationFor the layoutinfrastructure
  • 3. JavaScript engine: The JavaScript engine can explainJavaScript code, and through theDOM interface and CSS interfaceTo modify theWeb content and style informationAnd thus changeThe result of rendering
  • 4. Layout: After the DOM is created, WebKit needs to match the elements in the DOM with the style informationcombiningAnd calculate theirSize, location, and other layout informationTo form one that expresses all the informationInternal representation model
  • 5. Paint module: UseGraphics libraryPlot the nodes of each page after the layout calculationThe image results

5. The general rendering process

Point 7 of problem 1, rendering the page, building the DOM tree, let’s talk about the general rendering process

  • 1. The browser parses the document from top to bottom
  • 2, meet HTML tag, callHTML parserParsing tokens into tokens (a token is a serialization of a tag text) and building a DOM tree (a piece of memory that holds tokens and establishes relationships between them)
  • 3, meet the style/link tag, call the corresponding parser to process the CSS tag, and buildCSS style tree
  • 4, meet script tag, callJavaScript engineHandle script tags, bind events, modify DOM /CSS trees, etc
  • 5. Merge the DOM tree and CSS into oneRender tree
  • 6. Render according to the render tree to calculate each node’sGeometry information(This process relies on the GPU)
  • 7. Finally, each nodedrawOn the screen

The ultimate star yao

6. CSS blocking and optimization

  • 1, the style in the style tag: byHTML parserTo parse,Don'tBlocks browser rendering (which can cause a “splash screen”), does not block DOM parsing
  • 2. CSS styles introduced by LinkCSS parserTo parse,willBlocking browser rendering blocks subsequent JS statement execution, not DOM parsing
  • 3. Optimization: Use CDN nodes to accelerate external resources, compress CSS, optimize CSS code (don’t use too many layers of selecters)

Note: If you look at the image below,HTMLandCSSIt’s parsed in parallel, so CSSHTML parsing is not blockedBut,It blocks the rendering of the entire page(Because the CSS and HTML have to be parsed together to render.)

7. JS blocking problem

  • 1.Js blocks subsequent DOM parsingThe reasons are: The browser does not know the contents of the following script. If it parses the following DOM first, and then the js deletes all the following DOM, then the browser is doing nothing. The browser cannot estimate the actions in the script, such as document.write, so it simply stops and waits until the script is finished. The browser then moves down to parse the DOM
  • 2,Js blocks page renderingThe reason is that you can also set the style of the DOM in js, and the browser will render a final result after the script is executed, avoiding unnecessary work.
  • 3,Js blocks subsequent JS executionFor example, you must import jQuery before bootstrap

8. Resource loading is blocked

Either CSS blocking or JS blocking does not block the browser from loading external resources (images, videos, styles, scripts, etc.)

The reason: The browser is always in a “send requests first” mode. Whenever a web request is involved, whether it is an image, a style, or a script, the browser sends the request first to get the resource. When the resource is used locally, it is up to the browser to coordinate. It’s very efficient.

9. Why is the CSS parsed from right to left

If from left to right:

  • 1. The first time fromParent node -> child node -> grandson node 1
  • 2. The first time fromParent node -> child node -> grandson node 2
  • 3. The first time fromParent node -> child node -> grandson node 3

If you can’t match it three times, then you have to go at least three times: grandparent -> child -> grandchild, which is a lot of useless work.

If it’s from right to left:

  • 1. The first time fromSun node 1Can’t find, stop
  • 2. The first time fromSun node 2Can’t find, stop
  • 3. The first time fromSun node 3Can’t find, stop

In this way, as soon as possible to find can not be found, as soon as possible to stop, you can reduce a lot of useless work.

Most of the king

10. What is redraw reflux

  • 1. Redraw: Redraw is aChanges to the appearance of the elementTriggered browser behavior, such as changing the outline, background color, and other properties. The browser redraws the element based on its new attributes, giving it a new look. Redrawing does not entail rearrangement, so it does not necessarily accompany rearrangement.
  • Reflow: The render object does not contain location and size information when it is created and added to the render tree.The process of calculating these values is called layout or rearrangement, or backflow
  • 3,"Redraw" doesn't necessarily mean "rearrange."For example, changing the color of a page element will only trigger a “redraw”, not a “rearrangement”, because the layout has not changed.
  • 4,"Rearrange" in most cases will lead to "redraw"“For example, changing the position of an element on a web page triggers both” rearrange “and” redraw “because the layout has changed.

11. Properties that trigger redraw

* color * background * outline-color * border-style * background-image * outline * border-radius * background-position * outline-style * visibility * background-repeat * outline-width * text-decoration * background-size * box-shadow

12. Properties that trigger reflux

* width * top * text-align * height * bottom * overflow-y * padding * left * font-weight * margin * right * overflow * display * position * font-family * border-width * float * line-height * border * clear * vertival-align * min-height * white-space

13. Common triggers to redraw backflow

  • Reflow, Repaint when you add, delete, or modify a DOM node.
  • 2. When you move the DOM
  • 3. When you change CSS styles.
  • 4, when you areResize(This is not an issue on mobile, because mobile zooming doesn’t affect the layout viewport)
  • 5. When you modify the pageThe default fontAt the right time.
  • 6. Get the DOMHeight or widthWhen, for example,ClientWidth, clientHeight, clientTop, clientLeft, offsetWidth, offsetHeight, offsetTop, offsetLeft, scrollWidth, scrollHeight, SCR OllTop, scrollLeft, scrollIntoView(), scrollIntoViewIfNeeded(), getComputedStyle(), getBoundingClientRect(), scrollTo()

14. Optimal scheme for redrawing reflux

  • 1. CSS3 should be used as far as possible when element position is moved and transformedtransformTo take the place ofThe top and leftOperations such as
  • 2. Don’t use ittablelayout
  • Operations that will change the style properties multiple timesMerge into one operation
  • 4, the use ofdocumentFragment, vue uses this method to improve performance
  • 5, animation implementation process, enableTransform :tranlateZ(0)
  • 6, for animation elementsCreate a new layerTo improve the animation elementsz-index
  • 7. When writing animations, try to userequestAnimationFrame

15. Browser cache classification

  1. Strong cache
    1. Instead of sending a request to the server, the data is fetched directly from the local cache
    2. The status code of the requested resource is: 200 ok(from memory cache)
    3. Priority:cache-control > expires
  2. Negotiate the cache
    1. The request is sent to the server, and the server determines whether the negotiation cache is matched based on the resources in the request header
    2. If it hits, it returns304The status code tells the browser to read the resource from the cache
    3. Priority:Last-modified and ETag can be used together, the server will authenticate firstETagOnly if they are consistent will they continue to matchLast-ModifiedBefore deciding whether to return304

conclusion

For study group, please click here