Some pictures in the article are copied from the study article, but forget to store the article address ~

HTML Basics

HTML is a tag language, not assembly language

2. The difference between SVG and Canvas

SVG is a language for describing 2D graphics using XML.

Canvas uses JavaScript to draw 2D graphics.

SVG is based on XML, which means that every element in the SVG DOM is available. You can attach JavaScript event handlers to an element.

In SVG, every graph that is drawn is treated as an object. If the attributes of an SVG object change, the browser can reproduce the graphics automatically.

Canvas is rendered pixel by pixel. In canvas, once the graph has been drawn, it doesn’t continue to get attention from the browser. If its position changes, the entire scene also needs to be redrawn, including any objects that may have been covered by the graph.

3. Comparison between Canvas and SVG

The following table lists some differences between Canvas and SVG.

Canvas SVG
  • Resolution dependent
  • Event handlers are not supported
  • Weak text rendering capability
  • Ability to save the resulting image in.png or.jpg format
  • Best suited for graphics-intensive games, where many objects are frequently redrawn
  • Resolution independent
  • Support event handlers
  • Best for applications with large rendered areas (such as Google Maps)
  • High complexity slows down rendering (any application that overuses DOM is not fast)
  • Not suitable for game applications

4, HTML5 provides drag and drop functions, koala drag can try to use this attribute to achieve

5. Manifest cache, you can try caching page data

6. Web Workers: THE HTML page cannot respond when the script is executed on the page until the script is finished. Web Workers are JS operating in the background, independent from other scripts, which does not affect performance and can do anything without access to window, document and parent

7. Server-sent Event (SSE) : events sent by the server can be obtained (the client actively asks whether updates are available).

7, 8 have similar functions, establish communication between the browser and the server, the difference is that webSocket is a full-duplex channel, two-way communication can be stronger, SSE is single communication, can only be sent to the browser server, webSocket is a new protocol, need server support; SSE is established on the HTTP protocol, server software support;

8, WebSocket: allows the server to actively push data to the client (previously to achieve this function requires constant rotation to send requests to the server), only need to sink a handshake, you can create persistent links, and two-way data transmission.

Browser rendering

1. The process of entering HTML in the browser

DNS Domain name resolution Obtains the Ip address of the server (DNS query) = browser sends a GET request to the server (TCP connection, HTTP request) = Server returns resources (server response) = Browser downloads and parses HTML (client rendering)

Client-side rendering

Handle HTML tags to build a DOM tree = handle CSS tags to build a CSSOM tree = MERGE DOM and CSSOM into a render tree = layout, calculate geometric information for each node = draw to the screen

2. HTML includes DOM, CSS, JS and other parts. The parsing here is mainly the parsing process of DOM

Dom parsing is sequential (parsed from top to bottom) and progressive (the return portion of the parsing is immediately displayed)

We know that HTML parsing actually generates a DOM tree and a CSSDOM tree, and then merges them into a Render tree

This is a gradual process, with the rendering engine striving to get content on the screen as quickly as possible for a better user experience. It doesn’t have to wait until the entire HTML document has been parsed to start building the rendering tree and setting up the layout.

Window. onload and DomContentLoad

DomContentLoad: The dom number is completed, where a non-blocking resource does not block the build, and the Document object sends the event DomContentLoad to notify it

Window. onliad: All resources are loaded, including non-blocking resources

5, the resolution can only have external resources, divided into blocking, non-blocking type

Dom tree build = “defer JS execution =” DOM tree parse = “document send event =” non-blocking resource load complete = “window.onload

Blocking: inline CSS, inline JS, normal JS, defer JS, and the CSS before the JS tag

Non-blocking: external async JS, external CSS, image, and iframe after the JS tag

6. Connect ordinary JS

Outreach defer js

Outreach async js

DOMContentedLoaded code compatibility

Document. Readystate state to validate the DOM tree

  • Oading – HTML document loading
  • Interactive – HTML documents have been loaded and parsed, but images and other resources have not been loadedDOMContentLoaded
  • Complete – All resources are loaded, equivalent towindow onload
If (document. The readystate = = = 'interactive' | | document. The readystate = = = 'complete') {/ / ready callback function called} else { Document. The onreadystatechange = function () {if (document. The readystate = = = 'interative') {/ / ready callback function called}}}Copy the code

8. Browser structure

User interface: Displays the interface seen by the user (including the address bar, toolbar, and status bar. All parts displayed except the page displayed in the main browser window belong to the user interface)

Browser engine: Transfer instructions between the user interface and the rendering engine

Rendering engine: responsible for displaying the requested content; Parse the HTML, CSS content, generate the Render tree, and then assign each node to screen coordinates (layout) to facilitate rendering the tree

Network: Resource request

User interface backend: Used to draw basic widgets (combo boxes, Windows, etc.) without the platform providing the underlying implementation (drawing each node)

Js interpreter: Used to parse and execute JS code

Data storage: Hard disk stores all kinds of data (cookies, etc.)

Build = parse = Layout = draw

Principles of browsers

Data: www.html5rocks.com/zh/tutorial…

1, rendering engine: two engines (Firefox = “Gecko, Safari, Chrome =” WebKit support MAC and Windows)

2. Organize the process

Build: HTML to content tree + CSS file style tree = render tree

The rendering tree contains several rectangles with visual attributes, and the order of the rectangles is the order in which they are displayed on the screen

Layout: Each node is assigned an exact coordinate of the screen that appears

Draw: Traverse the rendering tree, drawing each node by the user interface back-end layer

Instead of waiting for the entire HTML document to be parsed to start building the rendering tree and setting up the layout, the rendering engine parses and displays portions of the web while accepting and processing the rest of it

3. Parsing: Turning documents into meaningful structures,

Analysis needs to be based on rules of grammar (lexical rules, preemptive rules)

Lexical analysis: Input is segmented into a large number of markers that can be understood as words in a language dictionary

Parsing: The process of applying the grammatical rules of a language

Interpretation process: lexical analyzer (the input content is decomposed into a valid tag), parser (root language grammar rules analysis document structure to build parsing tree); The parser requests a new tag from the lexical analyzer to obtain the tag matching grammar rules. The matching succeeds and the corresponding tag node is added to the parse tree to proceed to the next tag. If no match is found, the tag is stored internally and the tag continues to be requested until a rule that matches all the tags stored in the content is found; If no rule is found, the parser raises an error

Parsers: top-down parsers, bottom-up parsers

4. Translation: The compiler compiles the source code into machine code (parses the source code into a parse tree and then translates the parse tree into machine code)

5. HTML parsing:

Algorithm: tokenization, tree construction

Tokenization: lexical analysis process, HTML tags include start tags, end tags, attribute names, attribute values; The tag generator recognizes the tag, passes it to the tree constructor, and then accepts the next character to recognize the next tag, returning until the input ends

6. CSS parsing

Context-free syntax

Webkit: A bottom-up shift reduction parser

Firefox: Manual top-down parser

7. Sequence of scripts and stylesheets

Script: Javascript tags are encountered and the contents of the script are parsed and executed immediately, and parsing of the document is stopped until the script is finished. If it is external, it will download and execute and continue; Defer is executed at the end of the document without stopping parsing. Async is asynchronously parsed and executed by other threads

Pre-parsing: Other threads parse the document to find resources that need to be loaded over the network, and then load the resources in parallel links to improve speed. Pre-parsing does not modify the DOM, but only parses external resources

Stylesheets: The DOM tree is not changed, CSS before JS is parsed, and CSS after JS does not affect parsing

8. Present the tree

It lets you draw content in the correct order, and the elements in the rendering tree become renderers

Renderer: How to lay out and draw itself and its children, a rectangular area

Renderers correspond to elements of the DOM, but not one to one. A non-visual DOM does not insert a rendering tree (head, elements with display of None), and a DOM element has multiple renderers (select elements have three renderers).

9. Style calculation

The visual properties of each render object are computed when building the render tree

10, layout,

The rendering tree does not contain positions and sizes, and these values are calculated as layouts; Layout is a recursive process that traverses part or all of the framework hierarchy recursively, starting with the renderer

The root renderer position is 0 to the left, and its size is viewport (the visible area of the browser window). All renderers have a layout or reflow, and each renderer calls its child layouts that it needs to layout

Dirty committee system: Renderer changes will mark themselves and their children as Dirty.

Global layout (screen size changes, global style changes, affecting the entire render tree layout) and incremental layout (layout dirty renderers)

11, draw

Drawing is done using user interface infrastructure components

Global and incremental drawing

Draw order: The order in which elements are drawn into the style context of the stack, which is drawn from back to front. Quick renderer stack order: Background color = Background image = border = children = outline

12. The rendering engine is single-threaded, and all operations (except network operations) are single-threaded

13. Positioning scheme

Common: Locate the object based on its position in the document

Float: Layout as normal flow, then move as far left or right as possible

Absolute: The position of the object in the rendering tree is different from that in the DOM tree

Position: static, relative normal flow; Absolute and fixed Indicates the absolute location

Browser cache

1. Enforce caching

Mandatory cache: search the browser cache for the result of the request, and decide whether to use the cached result according to the result cache rule.

Caching rules that enforce caching: When the browser makes a request, the server sends the caching rules back to the browser in the HTTP header of the HTTP response header along with the request result

Controls fields that are force-cached: Expires and cache-control, with cache-control taking precedence over Expires

Expires: A field that controls the cache in HTTPS /1.0. Its value is the cache expiration time (server time) returned by the server. The client decides to use the cache if the time is less than the Expires time. One problem is that there may be errors in the comparison between the client time and the server time, forcing the cache to fail. The comparison time is used in combination with last-Modified

Cache-control: in HTTP /1.1, values:

Public: All content is cached (both client and proxy servers can cache)

Private: All content can be cached only by clients. Default value

No-cache: indicates the contents of the client cache, but the negotiation cache is required to verify whether to use the cache

No-store: All content is not cached. Neither mandatory caching nor protocol caching is used

Max-age =xx: The cache content expires after xx seconds

S-maxage =xx: applies only to the proxy server (CDN)

Cache-control is a better option than Expires in cases where you can’t determine whether the client’s time is synchronized with the server’s, so only cache-Control works when both exist

Source of cache: servic worker (user defined cache on hard disk), from memory cache (using memory cache), from disk cache (using disk cache), browser cache read order memory = “disk”

Memory cache: fast reads (stored directly in the process’s memory for quick reads next time) and timeliness (memory is emptied when the process is shut down)

Disk cache: Disk files are stored, but disk files are read from the cache. Disk file I/O operations are required, which is slower than memory cache

Browser: JS/image files are stored in memory, CSS is stored in hard disk files

2. Negotiate cache

After the Cache expires, the browser sends a request to the server with the Cache identifier. The server decides whether to use the Cache based on the Cache identifier

Negotiation cache field: Last-modified/if-modified-since and Etag/ if-node-match, where Etag/ if-none-match has a higher priority than last-modified/if-modified-since

Last-modified (in response header) : When the server responds to a request, returns the time when the resource file was Last Modified by the server

If-modified-since (in the request header) : When the client initiates a request again, it carries the last-Modified value and tells the server the time when the Last request was returned to the Last Modified value through the field. Then it determines whether to return the resource again. 304 indicates that the resource has no update and continues to use the cache

Last-modified malpractice: If the cache file is opened locally and not modified, last-Modified modification is also caused. The server cannot hit the cache and sends the same resource. Last-modifield is timed in seconds. If a file is modified in an imperceptible amount of time (multiple changes within 1 second), the server will task for a resource hit and will not return the correct resource

Etag: the server responds to a request to return a unique identifier for the current resource file (server generated)

If-none-match: the client sends a request with the Etag returned last time. The client checks whether the resource value is the same as the server’s Etag value. If the resource value is the same, the client returns 304 and uses the cache directly

3. The mandatory-cache takes precedence over the protocol Cache. If mandatory-cache (Expires, cache-control) takes effect, the protocol Cache is used; otherwise, the protocol Cache is used

4. Influence of user behavior

Enter the address in the address bar to check whether the disk cache matches the network request

Common refresh: Memory cache is used first, disk cache is used second

Forced refresh: Browsers do not use caching

5. Other Web caching strategies

IndexDB: local database provided by the browser

Service Worker: Offline cache

LocalStorage: allows access to the document object Storage the user stores the current source of data, unless the user is aware of, will be retained for a long time

SessionStorage: cleared at the end of a page session, retained by reloading or resuming the page

6. Cache classification

CDN cache

DNS cache

Client cache

Service workers and caching and offline caching

PageCache with Ajax cache

Network request

1. HTTP request: Domain name resolution (hosts file resolution, browser cache resolution, DNS resolution IP address location) = Initiate TCP three-way handshake = Initiate HTTP request after ESTABLISHING TCP connection = The server responds to HTTP request and returns resources = Parse HTML code and request external resources = Render and display to the user

2, DNS resolution:

The browser cache looks up the IP address of the domain name =

If you look it up in the operating system cache, it will look up this season’s HSOT =

Router lookup, router also has DNS cache =”

Initiate resolution request to LDNS (Internet Service Provider ISP) (recursive lookup) =

Search the root DNS server for a cache hit (iterated query) =

The root LDNS could not find the IP but told the domain’s authorization server =.

LDNS queries the domain authorization server =

Query your ZONE file (ZONE file record) to obtain the IP address return LDNS =

LDNS local cache, returned to the computer’s parser = “the parser is cached in the OPERATING system’s DNS cache, returned to the browser, browser cache for a period of time

Can be koala DNS-Prefetch optimization

3, cross-domain: nginx, CORS, JSONP, postMessage, webSocket

4. Send the HTTP request

Ajax: Encapsulation of the web API’s native XHR

Fetch: Continue with the Promise design, older browsers don’t support Promises, so a polyfill is required; Is the underlying API of the Web

Axios: Wrapper around native XHR, available in Node, supports Promise, and provides a concurrent request interface