First, browser rendering principle


  • Browser process: The main process of the browser, which is responsible for interface display, user interaction, child process management, and storage management.
  • GPU process: 3D drawing, enabling hardware acceleration to improve user experience.
  • Plug-in process: Manages the running of browser plug-ins.
  • Network process: Processes network resources.
  • Render process: Used to render pages.

A classic question: What happens when the user enters a URL carriage return? From a browser process perspective:

  1. The user type in the URL and press Enter,Browser processThe address is generated based on the default engine and navigation begins.
  2. Network processLoad the resource. After loading, hand inRendering processRender the page.
  3. Rendering processTo render the page.

Network seven-layer model:

  1. Physical layer (bit stream) : physical addressing, bit transfer.
  2. Data link layer (data frame, plus frame header and frame tail) : node-to-node data transmission; Framing, physical addressing, flow control, error control.
  3. Network layer (datagram, plus IP) : Packet delivery from source host to destination host. Logical addressing, routing, packet forwarding.
  4. Transport layer (data segment) : Complete packet transmission between end-to-end processes. SAP addressing, end-to-end connection, flow, error control.
  5. Session layer, presentation layer, and application layer: session control, codec encryption, and packet.

HTTP protocol history:

  1. HTTP 0.9 was responsible for transferring HTML. There were no request headers or response headers, and the browser handled strings directly.
  2. HTTP 1.0 provides HTTP headers, which are used to handle different resources.
  3. HTTP 1.1 enables keep-alive link multiplexing and pipelining by default (sending six requests simultaneously). Server response order, there is a queue head blocking problem.
  4. HTTP 2.0 multiplexing (sending data over the same TCP connection), header compression (colon), binary transport, server push data.
  5. HTTP 3.0 solves the problem of TCP queue header blocking by using UDP instead of TCP and adding THE QUIC protocol on top of UDP.

Process combing:

  1. DNS Resolves a domain name to an IP address.
  2. Cache lookup to check whether the cache is expired.
  3. The request is HTTPS for SSL negotiation.
  4. IP addresses are addressed and queued. A maximum of six HTTP requests can be sent.
  5. TCP creates a connection and shakes hands three times.
  6. Using TCP to transfer data (unpack, group, order, reliably transfer) the server receives it in order.
  7. Making an HTTP request (request line, request header, request body)
  8. Keep-alive will not be disconnected by default to ensure that the next transmission of data is available and the connection created last time can be consumed.
  9. After the server receives the data (response line, response header, response body)
  10. The server returns 301,302 will be redirected
  11. The server returns 304 and queries the browser cache to return

What does the browser do when it accepts the resource? (Rendering process)

  1. The HTML is not recognized by the browser and needs to be parsed from top to bottom, turning the HTML into a DOM tree. (document)
  2. Browsers cannot parse plain text CSS styles. Instead, they need to parse CSS into styleSheets (CSSOM). (document.styleSheets)
  3. Figure out the specific style of each node in the DOM tree. (Attachment)
  4. Create a render (layout) tree and add the DOM tree visible nodes to the layout tree. And compute the coordinate position of the node rendering to the page. (layout)
  5. Through the layout tree, layers (according to positioning properties, transparency properties, transform properties, clip properties, etc.) are generated layer tree.
  6. Draw the different layers and transfer them to the composition thread. The final page is generated and displayed in the browser (Painting,Display).

A classic problem: why JS at the bottom of CSS at the top of HTML top-down parsing, encounter header references external styles, do not immediately load CSS style, but continue to parse HTML, HTML parsing is completed, and then to parse CSS, wait for CSS parsing is completed, rendering. (CSS does not block HTML parsing)

Placing styles at the bottom, rather than in the head, may cause redraw backflow. Because styles are not placed in the head, browsers don’t render the DOM until the CSS has been loaded and parsed. Instead, they draw the DOM once while parsing the HTML, and then draw it again after parsing the CSS.

JS execution blocks DOM parsing as well as DOM rendering. The JS should wait for the CSS above to finish loading, so that the page JS can manipulate the style.

A classic question: How is the DOM generated and rendered onto a page

Node simulates a browser sending an HTTP request, receives the response and parses it with HTML and CSS.

Second, the Perfomance API


Critical time node describe meaning
TTFB Time to first byte The elapsed time between the request and the return of the first byte of data
TTI Time to Interactive When the DOM tree is built, events can be bound
DCL DOMContentLoaded (Event time) When the HTML document is fully loaded and parsed, the DOMContentLoaded event is fired
L OnLoad (Event time) This alarm is triggered when all dependent resources are loaded
FP First Paint The time when the first pixel is drawn to the screen
FCP First Contentful Paint The first time to draw any text, images, non-blank nodes
FMP First Meaningful paint The first meaningful drawing is a measure of page usability
LCP Largest Contentful Paint The maximum page element loading time in viewPort
FID First Input Delay The time between the user’s first interaction with the page (clicking a link, clicking a button, etc.) and the page’s response to the interaction
performance.timing API meaning
navigationStart In the same browser context, the timestamp for the previous page (not necessarily the same domain as the current page) to unload, or equal to the fetchStart value if there was no previous page unload
unloadEventStart Timestamp of previous page unload (same domain as the current page), 0 if there is no previous page unload or if the previous page is in a different domain than the current page
redirectStart The time when the first HTTP redirect occurs. The value is 0 only when there is a redirect within the same domain name
redirectEnd The time when the last HTTP redirect is complete. The value is 0 only when there is a redirect within the same domain name
fetchStart The time when the browser is ready to grab the document using an HTTP request, before checking the local cache
domainLookupStart DNS start time of domain name query. If local cache (no DNS query) or persistent connection is used, the value is the same as the fetchStart value
domainLookupEnd The time when the DNS domain name query is completed. If local cache (no DNS query) or persistent connection is used, the value is the same as the fetchStart value
connectStart The time when the HTTP (TCP) connection is started, equal to the fetchStart value if it is a persistent connection. If an error occurs at the transport layer and the connection is re-established, this is the time when the newly established connection is started
secureConnectionStart Start time of the HTTPS connection. If the connection is not secure, the value is 0
connectEnd The HTTP (TCP) connection completion time (handshake completion), if persistent, is equal to the fetchStart value, and if an error occurs at the transport layer and the connection is re-established, this is the time when the newly established connection is completed
requestStart The time when the HTTP request started reading the real document (the connection was completed), including reading from the local cache, and the time when the new connection was established when the connection error was reconnected
responseStart The time when HTTP starts receiving a response (the first byte is retrieved), including reading from the local cache
responseEnd The time when the HTTP response is fully received (fetched to the last byte), including reading from the local cache
domLoading Start parsing the time to render the DOM tree, document. readyState becomes loaded, and the readyStatechange event is thrown
domInteractive When the DOM tree is parsed, document. readyState changes to interactive and a readyStatechange related event is thrown
domContentLoadedEventStart After DOM parsing is completed, the time when resources in the web page start to load represents the time node triggered by DOMContentLoaded event
domContentLoadedEventEnd After DOM parsing is completed, the time when resources in the web page are loaded (such as JS scripts are loaded and executed)
domComplete When the DOM tree is parsed and the resources are ready, Document.readyState becomes complete and the readyStatechange event is thrown
loadEventStart The load event is sent to the document, which is the time the LOAD callback starts executing, and has a value of 0 if no LOAD event is bound
loadEventEnd The time when the callback to the load event completes. If no load event is bound, the value is 0

White screen time: domLoading – navigateStart First screen time: domInteractive – navigateStart DNS query time: DomainLookupEnd – domainLookupStart TCP connection duration: connectEnd – connectStartrequest request duration: Domcomplete-dominteractive domReady time: Domcontentloadedeventend-fetchstart Onload time = Loadeventend-fetchstart

Gitee: Performance API

Third, network optimization strategy


  • Reduce the number of HTTP requests, reasonably embedded CSS,JS.
  • Reasonable setting of server side cache, improve server processing speed (strong cache, negotiated cache).
  • Avoid redirects, which slow down the response.
  • usedns-prefetch,DNSParsing.
  • Domain name sharding is used to store resources under different domain names. (A domain name can process a maximum of six TCP connection requests).
  • CDN is used to speed up access.
  • Gzip compression optimization, volume optimization of transmission resources (HTML, JS, CSS) images and videos do not do GZIP.
  • Load the resource priority.preload(Pre-request resources needed for the current page)prefetch(resources to be used in future pages) to cache data in the HTTP cache.
<link rel="preload" href="style.css" as="style">
Copy the code

Key render paths


The critical render path, which means that these processes are executed as soon as the render is performed.

Visual changes = style calculation = Layout (rearrangement) = Draw (redraw) = Composite render

  • Rearrangement: add or remove elements, change their size, move their position,Gets element location information.
  • Redraw: Changes the style of an element without changing the style of the element in the document flow.

How to reduce rearrangement redraw:

  1. Out of the document flow.
  2. The image specifies the width and height.
  3. Use CSS animations whenever possible. (only draw once) to enable GUP acceleration.
  4. Use will-change to extract a separate layer and the browser will notice it separately.

Static file optimization


1. Image optimization

Image format:

  • jpg
  • png
  • gif
  • webp
  • svg

Picture optimization:

  • Avoid empty SRC images, which also send requests.
  • Reduce image size, compress image, reduce user traffic.
  • Img tag with Alt attribute, image loading failure user experience.
  • Larger images use progressive images.
  • Small iconbase64Reduce image requests.
  • Native image lazy loading:Loading: lazy
<img loading="lazy" src="./images/1.jpg" width="300" height="450" />
Copy the code
  • Load images of different sizes and pixels in different environments
<img src="./images/1.jpg" sizes="(max-width:500px) 100px,(max-width:600px) 200px"  srcset="./images/1.jpg 100w, ./images/3.jpg 200w">
Copy the code

2. HTML optimization

  • Semantic HTML: search engine friendly and team friendly.
  • Declare the character set in advance so that the browser knows how to render web content.
  • Reduce meaningless DOM tags.
  • Reduce the use of iframe, which blocks onLoad events. Iframe can be loaded dynamically.
  • Avoid table layouts, which are rendered after the entire load is complete.

3. The CSS optimization

  • Fewer pseudo-class selectors, fewer style layers, and fewer wildcards.
  • Avoid CSS expressions, which are frequently evaluated.
  • Remove blank lines, comments, and nonsense units
  • CSS compression.
  • Using external chains, you can cache CSS.
  • css containProperty to isolate elements.
  • To use less@importIt is used to load through.

4. JS optimization

  • Async, deferLoad files asynchronously.

  • Reduce DOM manipulation and cache accessed elements.
  • Webworker solves application blocking problems. (Complex calculation)
  • IntersectionObserverMonitor the range of visual area.
const observer = new IntersectionObserver(function(changes) { 
    changes.forEach(function(element, index) {
        if (element.intersectionRatio > 0) { observer.unobserve(element.target); element.target.src = element.target.dataset.src; }}); });function initObserver() {
    const listItems = document.querySelectorAll('img');
    listItems.forEach(function(item) {
        observer.observe(item);
    });
}
initObserver();
Copy the code
  • Virtual rollingvertual-scroll-list.
  • requestAnimationFrame.requestIdleCallback
  • Reduce the number of event bindings by using event delegates.
  • Use Canvas animation, CSS animation.

Sixth, optimization strategy


  1. Number of resources loaded
  2. Resource volume size
  3. Resource preloading
  4. Server-side rendering, SEO.
  5. Number of interface requests
  6. Use of cache

PWA (Progressive Web App)


Webapp cannot be accessed offline, and users cannot save the entry.

  • Web App Minifest: Add Web sites to your desktop.
  • Service Worker: Offline cache content, with cache API.
  • Push API & Notification API: Message Push.
  • App Shell & App Skeleton: App Shell & App Skeleton

Use of LightHouse


npm install lighthouse -g
lighthouse --view http://www.baidu.com
Copy the code