Computer Basics Series - from entering the URL to a detailed page load process is completed, throughout the development of knowledge

Disclaimer: If there is infringement, please contact me, we grow and learn together. STAY CURIOUS. STAY HUMBLE. Https://blog.csdn.net/saucxs/article/details/90476340

I. Introduction

This question can be very broad coverage, it is suitable as a title bearer of knowledge. Each front-end staff, if you want to go higher order, it will certainly own knowledge comb it again, there is no solid body of knowledge, can not go to a higher place!

 

Second, the main flow

In the browser rendering principle , JS operational mechanism , JS engine parsing process after carding again, feeling just opened up, like Renduermai, with an overall framework, previous knowledge points are consistent up.

1, receiving the url from the browser to open a network request thread (related to: the relationship between the browser mechanism, threads and processes, etc.)

2, the thread open network to send a http request full (involves: dns query, tcp / ip requests, the network layer protocol stacks 5)

3, the request received from the server to the corresponding request is received back (it relates to: load balancing, security interceptors, processing inside the background, etc.)

4, the background and foreground http interactions (involving: http headers, response code, packet structure, Cookie, etc., can be improved optimization Cookie static resources, such as gzip compression codecs and the like)

5, caching issues: http cache (related to: http caching involves the head, etag, expired, cache-control, etc.)

6, the browser receives the http packet parsing process (involving: html lexical analysis, and then parsed into dom tree while parsing css generating css rule tree, combined to generate render tree and layout layout, Painting rendering composite FIG. synthetic layer, the GPU rendering, the outer link processing, and loaded documentloaded etc.)

7, css visual formatting model (involving: element rendering rules, such as: a block comprising a control block, BFC, IFC concepts)

8, js engine resolution process (involving: js interpretation stage, the pretreatment stage, execution stage generates an execution context, VO (global object), the scope chain, recovery mechanisms)

9 Other (Other expansion modules: cross-domain, web security, etc.)

 

Third, the browser receives from the url to open a network request thread

Related to: Process Explorer and threading model, js operating mechanism.

1, is a multi-process browser

(1) is a multi-process browser;

(2) different types of tabs will open a new process;

(3) of the same type tabs will be merged into a single process.

The browser and the role of each process :

1, the browser process: only one process, (1) is responsible for managing the creation and destruction of individual labels; (2) is responsible for the browser's page; (3) responsible for resource management and downloads;

2, third-party plug-in process: may be multiple processes, each responsible for using a third-party plug-ins, each a third-party plug-ins to use when will create a new process;

3, GPU process: up to a process responsible for 3D rendering and hardware acceleration;

4, the browser rendering process: may be multiple processes, browser kernel, a process for each tab page, is responsible for parsing HTML ,, css, js and other documents, execution and rendering, event handling, and so on.

 

2, browser rendering process (kernel processes)

Each page is a tab browser kernel process, then each process that is multi-threaded, it has a sub-thread categories:

(1) GUI thread; (2) JS engine thread; (3) event triggered thread; (4) the timer thread; (5) asynchronous http network request thread

Can see JS engine is a multithreaded kernel process, when it is often said that the single-threaded JS engine.

 

3, parse URL

After entering the url, it will be resolved (URL is a Uniform Resource Locator).

URL comprises several parts: (1) protocol, protocol header, such as http, https, ftp, etc.; (2) host, host domain name or IP address; (3) port, a port number; (4) path, directory path; ( 5) query, the query parameter; (6) fragment, # behind the hash values, used to locate a particular location.

 

4, when the network requests a separate thread

Each requires a separate network requests are opening up a separate thread, such as URL resolves to http protocol, it will create a new thread to handle network resources to download.

Therefore, the browser will have to parse out according to the agreement, to open up a network of threads, to the requested resource.

 

Fourth, open the network to issue a complete thread http request

Including: DNS queries, tcp / ip request to build, five Internet Protocol, and so on.

1, DNS queries get IP

If the domain name entered, DNS resolution needs to IP, process is as follows:

(1) There browser cache, browser cache directly, do not go to this local cache, not to see is not the host.

(2) if not, it queries the DNS domain name server (this process through routing, routing also cache), querying the corresponding IP.

Note: 1, when the domain name query is likely to pass CDN scheduler (CDN if a memory function);

2, DNS resolution is very time-consuming, so if too much resolve domain names, the first screen will be slow to load, consider using dns-prefetch optimization.

 

2, tcp / ip request construction

Http essence is the tcp / ip request to build. It requires three-way handshake resume regular connection, and four waving disconnect time.

http tcp The long message is divided into short packets, to establish a connection via 3-way handshake with the server, reliable transmission.

3-way handshake steps:

客户端:hello,你是server么?
服务端:hello,我是server,你是client么
客户端:yes,我是client

After successfully established, the next step is a formal data transmission.

Then, wait until the disconnected, it needs to be four wave (because it is full duplex, it is necessary to 4 way handshake).

4 waved steps :

主动方:我已经关闭了向你那边的主动通道了,只能被动接收了
被动方:收到通道关闭的信息
被动方:那我也告诉你,我这边向你的主动通道也关闭了
主动方:最后收到数据,之后双方无法通信

 

tcp / ip concurrency limit

Tcp concurrent browser connections under the same domain name is limited (ranging from 2-10). And in http1.0 often you need to download a resource corresponding to a tcp / ip request. So for this bottleneck, there was a lot of resource optimization.

 

get and post the difference

get and post are essentially tcp / ip, but in addition to http outer layer in tcp / ip levels are different. tcp get produce a packet, post produces two tcp packets.

Concrete is:

(1) When the get request, the browser will send the header and data go out, in response to the server 200 (return data).

(2) post request, the browser first transmission headers, server response 100 continue, retransmission Data browser, the server response 200 (return data).

 

3, five-layer network protocol stack

Http client makes a request to the server to receive, through a series of intermediate processes will.

Specific client sends a request: launch a http request from the application layer, transport layer to resume the three-way handshake tcp / ip connection, then the network layer address ip, and then encapsulated in a frame of the data link layer, the physical layer and finally by physical transmission media.

The server receiving a request specifically: turn.

Five-layer network protocols:

1, the application layer (DNS, HTTP): DNS to resolve the IP and send the http request;

2, the transport layer (TCP, UDP): establishes a TCP connection (3 way handshake);

3, the network layer (IP, ARP): IP address;

4, the data link layer (PPP): encapsulated in a frame;

5, the physical layer (the transmission bit stream using a physical medium): physical transmission (twisted pair, and other electromagnetic wave medium).

In fact, there is a full seven-layer OSI framework, compared with more than a session layer, presentation layer .

OSI seven-layer 物理层framework: 数据链路层, 网络层, 传输层, 会话层, 表示层, ,应用层

Presentation Layer : The main processing two way communication system showing interaction information , including data exchange format, data encryption and decryption, data compression and terminal type conversion.

Session layer: the specific management dialogue between different users and processes, such as control login and logout process.

 

Fifth, the server receives a request from the reception of the request corresponding to the background

When the server receives a request, there will be a lot of internal processing.

Include: load balancing,

1, load balancing

For large projects, concurrent access to a large, too much for a server, generally have several servers for a cluster, and then with a reverse proxy to achieve load balancing. More than one way to achieve load balancing.

In summary: the scheduling request sent by the user pointing to the server (reverse proxy server, such as load balancing nginx), then the scheduling server according to an actual scheduling algorithm, different allocation request to a corresponding server cluster performed, and the scheduler waits the actual HTTP response from the server, and feedback to the user.

2, background processing

General background are deployed to the container. Process is as follows:

(1) First, a container receiving the request (for example the container tomcat);

(2) Then the background program corresponding to the container receiving the request (such as java program);

(3) then that is their uniform background processing, after processing in response to the results.

Specific recap:

(1) there is usually some back-end unified authentication, such as security interception, cross-domain verification;

(2) If not validation rules, the corresponding direct return http message (request rejection and the like);

(3) if the verification is passed, will enter the actual code behind, when the program receives a request, a database query is then executed, a large number of calculation and the like;

(4) other program is finished, it will return a http response (typically multi-layer package will go through this step);

(5) the packet is then returned to the rear from the front end to complete the interaction.

 

http interaction Sixth, the background and foreground

Before and after the end of the interaction, http packets as a carrier of information.

1, http packet structure

Message generally includes: common header, the request / response header, the request / response thereof

1.1 Universal head

Request Url: 请求的web服务器地址

Request Method: 请求方式
(Get、POST、OPTIONS、PUT、HEAD、DELETE、CONNECT、TRACE)

Status Code: 请求的返回状态码,如200代表成功

Remote Address: 请求的远程服务器地址(会转为IP)

When such cross refused, methord for option, status code 404/405.

Wherein the method is divided into two batches:

HTTP1.0定义了三种请求方法: GET, POST 和 HEAD方法。
以及几种Additional Request Methods:PUT、DELETE、LINK、UNLINK

HTTP1.1定义了八种请求方法:GET、POST、HEAD、OPTIONS, PUT, DELETE, TRACE 和 CONNECT 方法。

For example, some status code to determine:

200——表明该请求被成功地完成,所请求的资源发送回客户端
304——自从上次请求后,请求的网页未修改过,请客户端使用本地缓存
400——客户端请求有错(譬如可以是安全模块拦截)
401——请求未经授权
403——禁止访问(譬如可以是未登录时禁止)
404——资源未找到
500——服务器内部错误
503——服务不可用

Approximate range

1xx——指示信息,表示请求已接收,继续处理
2xx——成功,表示请求已被成功接收、理解、接受
3xx——重定向,要完成请求必须进行更进一步的操作
4xx——客户端错误,请求有语法错误或请求无法实现
5xx——服务器端错误,服务器未能实现合法的请求

 

1.2 Head Request / Response Header

Common request header (part)

Accept: 接收类型,表示浏览器支持的MIME类型
(对标服务端返回的Content-Type)
Accept-Encoding:浏览器支持的压缩类型,如gzip等,超出类型不能接收
Content-Type:客户端发送出去实体内容的类型
Cache-Control: 指定请求和响应遵循的缓存机制,如no-cache
If-Modified-Since:对应服务端的Last-Modified,用来匹配看文件是否变动,只能精确到1s之内,http1.0中
Expires:缓存控制,在这个时间内不会请求,直接使用缓存,http1.0,而且是服务端时间
Max-age:代表资源在本地缓存多少秒,有效时间内不会请求,而是使用缓存,http1.1中
If-None-Match:对应服务端的ETag,用来匹配文件内容是否改变(非常精确),http1.1中
Cookie: 有cookie并且同域访问时会自动带上
Connection: 当浏览器与服务器通信时对于长连接如何进行处理,如keep-alive
Host:请求的服务器URL
Origin:最初的请求是从哪里发起的(只会精确到端口),Origin比Referer更尊重隐私
Referer:该页面的来源URL(适用于所有类型的请求,会精确到详细页面地址,csrf拦截常用到这个字段)
User-Agent:用户客户端的一些必要信息,如UA头部等

Response common header (part)

Access-Control-Allow-Headers: 服务器端允许的请求Headers
Access-Control-Allow-Methods: 服务器端允许的请求方法
Access-Control-Allow-Origin: 服务器端允许的请求Origin头部(譬如为*)
Content-Type:服务端返回的实体内容的类型
Date:数据从服务器发送的时间
Cache-Control:告诉浏览器或其他客户,什么环境可以安全的缓存文档
Last-Modified:请求资源的最后修改时间
Expires:应该在什么时候认为文档已经过期,从而不再缓存它
Max-age:客户端的本地资源应该缓存多少秒,开启了Cache-Control后有效
ETag:请求变量的实体标签的当前值
Set-Cookie:设置和页面关联的cookie,服务器通过这个头部把cookie传给客户端
Keep-Alive:如果客户端有keep-alive,服务端也会有响应(如timeout=38)
Server:服务器的一些相关信息

In general, request headers and response headers are matched analysis.

such as:

(1) the request header Acceptto the response header and Content-Typematching to avoid an error;

(2) cross-domain request, the request header to match the response of Origin header Access-Control-Allow-Origin, or cross-domain error will be reported;

(3) use of the cache, the request header if-modified-since, if-none-match, respectively, and the response headers Last-modified, etag correspondence.

 

1.3 请求/响应实体

http请求时,除了头部,还有消息实体。

请求实体中会将一些需要的参数都放入进入(用于post请求)。

比如:(1)实体中可以放参数的序列化形式(a=1&b=2这种),或者直接放表单(Form Data对象,上传时可以夹杂其他以及文件)等等。

响应实体中,就是服务端需要传给客户端的内容。

一般现在的接口请求时,实体中就是对应信息的json格式,而像页面请求这种,里面就是直接放一个html的字符串,然后浏览器自己解析并渲染。

 

1.4 CRLF

CRLF(Carriage-Return Line-Feed),意思是回车换行,一般作为分隔符存在。

请求头和实体消息之间有一个CRLF分隔,响应头部和响应实体之间用一个CRLF分隔。

下图是对某请求的http报文结构的简要分析:

 

2、 cookie以及优化

cookie是浏览器的一种本地存储方式,一般用来帮助客户端和服务端通信的,常用来进行身份校验,结合服务端的session使用。

在登陆页面,用户登陆了

此时,服务端会生成一个session,session中有对于用户的信息(如用户名、密码等)

然后会有一个sessionid(相当于是服务端的这个session对应的key)

然后服务端在登录页面中写入cookie,值就是:jsessionid=xxx

然后浏览器本地就有这个cookie了,以后访问同域名下的页面时,自动带上cookie,自动检验,在有效时间内无需二次登陆。

一般来说,cookie是不允许存放敏感信息的(千万不要明文存储用户名、密码),因为非常不安全,如果一定要强行存储,首先,一定要在cookie中设置httponly(这样就无法通过js操作了),另外可以考虑rsa等非对称加密(因为实际上,浏览器本地也是容易被攻克的,并不安全)

比如这样的场景:

客户端在域名A下有cookie(这个可以是登陆时由服务端写入的)

然后在域名A下有一个页面,页面中有很多依赖的静态资源(都是域名A的,譬如有20个静态资源)

此时就有一个问题,页面加载,请求这些静态资源时,浏览器会默认带上cookie

也就是说,这20个静态资源的http请求,每一个都得带上cookie,而实际上静态资源并不需要cookie验证

此时就造成了较为严重的浪费,而且也降低了访问速度(因为内容更多了)

当然了,针对这种场景,是有优化方案的(多域名拆分)。具体做法就是:

(1)将静态资源分组,分别放到不同的域名下(如static.base.com

(2)而page.base.com(页面所在域名)下请求时,是不会带上static.base.com域名的cookie的,所以就避免了浪费

 

说到多域名拆分,还有一个问题?

(1)在移动端,如果请求的域名数过多,会降低请求速度(因为域名整套解析流程很浪费时间,而且移动端一般带宽比不上PC)。

(2)这时候有个优化方案:dns-prefetch(这个是干嘛的?就是让浏览器空闲时提前解析dns域名,不过请合理使用)

 

关于cookie的交互,可以看下图总结

 

3、gzip压缩

首先,gzip是请求头里的Accept-Encoding:浏览器支持的压缩类型之一。gzip是一种压缩格式,需要浏览器支持才有效(一般浏览器都支持),而且gzip的压缩率很好(高达70%);

然后gzip一般是apach,nginx,tomcat等web服务器开启。

除了gzip的压缩格式,还有deflate,没有gzip高效,不流行。

所以一般只需要在服务器上开启gzip压缩,然后之后的请求都是基于gzip压缩格式的,非常方便。

 

4、长连接和短连接

首先我们看一下tcp/ip的定义:

(1)长连接:一个tcp/ip连接上可以连续发送多个数据包,tcp连接保持期间,如果乜有数据包发送,需要双方发检测包以维持此连接,一般需要自己做在线维持(类似于心跳包)。

(2)短连接:通信双方有数据交互是,简历一个tcp连接,数据发送完成后,则断开此tcp连接。

我们再看一下http层面上:

(1)http1.0中,默认是使用的短连接,浏览器每进行一次http操作,就建立一次连接,任务结束就中断连接,比如每一个静态资源请求都是一个单独的连接

(2)http1.1开始,默认是使用长连接,长连接会设置connection: keep-alive,在长连接的情况下,当一个网页打开后,客户端和服务端之间用于传输http的tcp连接不会关闭,如果客户端再次访问服务器这个页面,会继续使用这一条已经建立起来的连接。

注意:kee-alive不会永远保持,他有一个持续时间,一般服务中进行配置,另外长连接是需要客户端和服务器端都支持才有效。

 

5、http2.0

http2.0不是https,它相当于http的下一代规范(https也可能是http2.0规范)

比较一下http1.1和http2.0显著不同地方:

(1)http1.1中,每请求一个资源,都是需要开启一个tcp/ip连接的,所以对应的结果是:每一个资源对应一个tcp/ip请求,由于tcp/ip本身有个并发数的限制,资源一旦多了,速度会下降慢下来。

(2)http2.0中,一个tcp/ip请求可以请求多个资源,也就说,只要一次tcp/ip请求,就可以请求多个资源,分隔成更小的帧请求,速度明显提升。

所以,如果http2.0全面应用的,很多http1.1中的优化方案无需用到(比如:精灵图,静态组员多域名拆分等)。

现在介绍一下http2.0的一些特性:

(1)多路复用(一个tcp/ip可以请求多个资源);

(2)首部压缩(http头部压缩,减少体积);

(3)二进制分帧(在应用层跟传输层之间增加一个二进制分帧层,改进传输性能,实现低延迟和高吞吐);

(4)服务器端推送(服务端可以对客户端的一个请求发出多个响应可以主动通知客户端);

(5)请求优先级(如果流被赋予了优先级,就会基于这个优先级来处理,有服务器决定需要多少资源来处理该请求)

 

6、https

https就是安全版本的http,比如一些支付操作服务基本上都是基于https的,因为http请求的安全系数太低了。

简单来看,https和http区别是:在请求前,会建立ssl链接,确保接下来的通信都是加密的,无法轻易截取分析。

一般来说,需要将网站升级到https,需要后端支持(后端需要申请证书等),然后https的开销比http大(因为要额外的简历安全链接和加密等),所以一般来说http2.0配合https的体验更佳(http2.0更快)。

主要关注的就是SSL/TLS的握手流程,如下(简述):

(1)浏览器请求建立SSL链接,并向服务端发送一个随机数(client random)和客户端支持的加密方法,比如是RSA加密,此时是明文传输。

(2)服务端从中选出一组加密算法和hash算法,回复一个随机数(server random),并将自己的身份信息以证书的形式发回给浏览器(证书中包含了网站地址,非对称加密的公钥,以及证书颁发机构等信息)。

(3)浏览器收到服务端证书后:

1、首先验证证书的合法性(颁发机构是否合法,证书包含的网站是否和正在访问的一样),如果证书信任,浏览器会显示一个小头锁,否则会有提示。

2、用户接受到证书后(不管信任不信任),浏览器会产生一个新的随机数(Premaster secret),然后证书中的公钥以及制定的加密方法加密`Premaster secret`(预主密码),发送给服务器。

3、利用client random,server random 和 premaster secret 通过一定的算法生成HTTP链接数据传输的对称加密key-‘sessionkey’

4、使用约定好的hash算法计算握手消息,并使用生成的session key 对消息进行加密,最后将之前生成的所有信息发送给服务端。

(4)服务端收到浏览器的回复

1、利用已知的加密方式与自己的私钥进行解密,获取Premaster secret,

2、和浏览器相同规则生成session key,

3、使用session key 解密浏览器发来的握手消息,并验证hash是否与浏览器发来的一致,

4、使用session key 加密一段握手消息,发送给浏览器

(5)浏览器解密并计算握手消息的hash值,如果与服务端发来的hash一致,此时握手结束。

之后所有的https通信数据将由之前浏览器生成的session key并利用对称加密算法进行加密

 

七、缓存问题:http缓存

http交互中,缓存很大程度上提升效率。

1、强缓存与弱缓存

缓存可以简单划分为两种类型:强缓存(200 from cache)与协商缓存(304);

区别简介一下:

(1)强缓存(200 from cache)时,浏览器如果判断本地缓存未过期,就直接使用,无需发起http请求。

(2)协商缓存(304)时,浏览器会向服务器发起http请求,然后服务端告诉浏览器文件未改变,让浏览器使用户本地缓存。

对于协商缓存,可以使用ctrl + F5强制刷新,使得协商缓存无效。

对于强制缓存,在未过期,必须更新资源路径才能发送新的请求。

 

2、缓存头部简述

怎么在代码中区分强缓存和协商缓存?

通过不同的http的头部控制。

 

属于强制缓存的:

(http1.1)Cache-Control/Max-Age
(http1.0)Pragma/Expires

注意:cache_control的值:public,private,no-store,no-cache,max-age

属于协商缓存的:

(http1.1)If-None-Match/E-tag
(http1.0)If-Modified-Since/Last-Modified

 

再提一点,其实HTML页面中也有一个meta标签可以控制缓存方案-Pragma

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">

不过,这种方案还是比较少用到,因为支持情况不佳,譬如缓存代理服务器肯定不支持,所以不推荐。

 

3、缓存头部区别

在http1.1中,出现了一些新内容,弥补http1.0不足。

http1.0中的缓存控制:

(1)Pragma:严格来说不算缓存控制的头部,设置了no-cache会让本地缓存失效(属于编译控制,来实现特定的指令)。

(2)Expires:服务端配置,属于强缓存,用来控制在规定的时间之前,浏览器不会发送大量请求,而直接使用本地缓存,注意:Expires一般对应服务器端时间,比如:Expires:Fri, 30 Oct 1998 14:19:41

(3)If-Modified-Since/Last-modified:这两个是成对出现的,属于协商缓存。其中浏览器头部是If-Modified-Since,而服务端是Last-Modified,发送请求时,如果这两个匹配成功,代表服务器资源并没有改变,服务端不会返回资源实体,而是返回头部,告知浏览器使用本地缓存。Last-modifed指文件最后的修改时间,只能精确到1S以内。

http1.1中缓存的控制:

(1)cache-control :缓存的控制头部,有nocache,max-age等多个取值。

(2)Max-Age:服务端配置的,用来控制强缓存的,在规定的时间内,浏览器不用发出请求,直接使用本地的缓存。Max-Age是cache-control的值,比如:cache-control: max-age=60*1000,值是绝对时间,浏览器自己计算。

(3)If-None-Match/E-tag:这两个是成对的出现的,属于协商缓存,其中浏览器头部是If-None-Match,而服务端是E-tag,同样,发出请求后,如果If-None-Match和E-tag匹配,代表内容没有变化,告诉浏览器使用本地缓存,和Last-modified不同,E-tag更精确,它类似于指纹一样,基于FileEtag INode Mtime Size生成的,就是说文件变,指纹就会变,没有精确度的限制。

 

Cache-Control相比Expires?

1、都是强制缓存。

2、Expires使用服务端时间,因为存在时区,和浏览器本地时间可以修改问题,在http1.1不推荐使用Expires;Cache-Control的Max-Age是浏览器端本地的绝对时间。

3、同时使用Cache-Control和Expires,Cache_control优先级高。

 

E-tag相比Last-Modified?

1、都是协商缓存。

2、Last-modified指的是服务端文件最后改变时间,缺陷是精确只能到1s,文件周期性的改变,导致缓存失效;E-tag是一种指纹机制,文件指纹,只要文件改变,E-tag立刻变,没有精度限制。

3、带有E-tag和Last-modified时候,E-tag优先级高。

 

各大缓存头部的整体关系如下图

 

八、解析页面流程

前面提到是http交互,接下来是浏览器获取到html,然后解析,渲染。

1、流程简述

浏览器内核拿到内容后,渲染大致分为以下几步:

(1)解析html,构建DOM树;同时解析CSS,生成CSS规则树。

(2)合并DOM树和CSS规则树,生成Render树。

(3)布局Render树(layout/reflow),负责各元素的尺寸,位置计算。

(4)绘制render树(paint),绘制页面像素信息。

(5)浏览器会将各层的信息发给GPU。GPU会将各层合成(composite),显示在屏幕上。

如下图:

 

2、html解析,构建DOM

这一步的流程是这样的:浏览器解析HTML,构建DOM树。实际上,稍微展开一下。

解析html到构建dom过程简述如下:

Bytes -> characters -> tokens -> nodes ->DOM

比如,有这样一个html页面:

<html>
  <head>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="style.css" rel="stylesheet">
    <title>Critical Path</title>
  </head>
  <body>
    <p>Hello <span>web performance</span> students!</p>
    <div><img src="awesome-photo.jpg"></div>
  </body>
</html>

浏览器的处理如下:

列举一下其中一些重点过程:

1. Conversion转换:浏览器将获得的HTML内容(Bytes)基于他的编码转换为单个字符

2. Tokenizing分词:浏览器按照HTML规范标准将这些字符转换为不同的标记token。每个token都有自己独特的含义以及规则集

3. Lexing词法分析:分词的结果是得到一堆的token,此时把他们转换为对象,这些对象分别定义他们的属性和规则

4. DOM构建:因为HTML标记定义的就是不同标签之间的关系,这个关系就像是一个树形结构一样
例如:body对象的父节点就是HTML对象,然后段略p对象的父节点就是body对象

最后的DOM树:

3、css解析,构建css规则树

CSS规则树的生成也是类似

Bytes → characters → tokens → nodes → CSSOM

比如:style.css内容如下:

body { font-size: 16px }
p { font-weight: bold }
span { color: red }
p span { display: none }
img { float: right }

最终的CSSOM树就是

 

4、构建渲染树

当DOM树和CSSOM都有了后,就要开始构建渲染树了。一般来说,渲染树和DOM树相对应的,但不是严格意义上的一一对应。

因为有一些不可见的DOM元素不会插入到渲染树中,如head这种不可见的标签或者display: none

 

5、渲染

有了render树,接下来就是开始渲染,基本流程如下:

图中重要的四个步骤就是:

(1)计算CSS样式 ;

(2)构建渲染树 ;

(3)布局,主要定位坐标和大小,是否换行,各种position overflow z-index属性 ;

(4)绘制,将图像绘制出来。

然后,图中的线与箭头代表通过js动态修改了DOM或CSS,导致了重新布局(Layout)或渲染(Repaint)

 

这里Layout和Repaint的概念是有区别的:

(1)Layout,也称为Reflow,即回流。一般意味着元素的内容、结构、位置或尺寸发生了变化,需要重新计算样式和渲染树。

(2)Repaint,即重绘。意味着元素发生的改变只是影响了元素的一些外观之类的时候(例如,背景色,边框颜色,文字颜色等),此时只需要应用新样式绘制这个元素就可以了。

回流的成本开销要高于重绘,而且一个节点的回流往往回导致子节点以及同级节点的回流, 所以优化方案中一般都包括,尽量避免回流。

 

6、什么引起回流

1.页面渲染初始化

2.DOM结构改变,比如删除了某个节点

3.render树变化,比如减少了padding

4.窗口resize

5.最复杂的一种:获取某些属性,引发回流,
很多浏览器会对回流做优化,会等到数量足够时做一次批处理回流,
但是除了render树的直接变化,当获取一些属性时,浏览器为了获得正确的值也会触发回流,这样使得浏览器优化无效,包括
    (1)offset(Top/Left/Width/Height)
     (2) scroll(Top/Left/Width/Height)
     (3) cilent(Top/Left/Width/Height)
     (4) width,height
     (5) 调用了getComputedStyle()或者IE的currentStyle

回流一定伴随着重绘,重绘却可以单独出现。

优化方案:

(1)减少逐项更改样式,做好一次性更改样式。或者将样式定义为class,并一次性更新。

(2)避免循环操作dom,创建一个documentFragment或div,在他上面进行所有的dom操作,最后添加到window.document中。

(3)避免多次读取offset等属性,无法避免就将他们缓存到变量中。

(4)将复杂的元素绝对定位或者固定定位,使他们脱离文档流,否则回流代价很高。

注意:改变字体大小会引起回流。

再看一个例子:

var s = document.body.style;

s.padding = "2px"; // 回流+重绘
s.border = "1px solid red"; // 再一次 回流+重绘
s.color = "blue"; // 再一次重绘
s.backgroundColor = "#ccc"; // 再一次 重绘
s.fontSize = "14px"; // 再一次 回流+重绘
// 添加node,再一次 回流+重绘
document.body.appendChild(document.createTextNode('abc!'));

 

6、简单层和复合层

上述中的渲染中止步于绘制,但实际上绘制这一步也没有这么简单,它可以结合复合层和简单层的概念来讲。

简单介绍下:

(1)可以默认只有一个复合层,所有的DOM节点都是在这个复合图层下。

(2)如果开启了硬件加速功能,可以将某一个节点变成复合图层。

(3)复合图层之间的绘制互不干扰,直接GPU直接控制。

(4)简单图层中,就算是absolute等布局,变化时不影响整体回流,但是由于在同一个图层中,仍然会影响绘制的,因此做动画时候性能仍然很低。而且复合层是独立的,所以一般做动画推荐使用硬件加速。

更多参考:https://segmentfault.com/a/1190000012925872#articleHeader16

 

7、Chrome的调试

Chrome的开发者工具中,Performance中可以看到详细的渲染过程:

 

8、资源外链的下载

上面介绍了html解析,渲染流程。但实际上,在解析html时,会遇到一些资源连接,此时就需要进行单独处理了。

简单起见,这里将遇到的静态资源分为一下几大类(未列举所有):

(1)css样式资源

(2)js脚本资源

(3)img图片类资源

 

(1)遇到外链的处理

当遇到上述的外链时,会单独开启一个下载线程去下载资源(http1.1中是每一个资源的下载都要开启一个http请求,对应一个tcp/ip链接)

 

(2)遇到css样式资源

css资源处理特点:

(1)css下载时异步的,不会阻塞浏览器构建DOM树;

(2)但是会阻塞渲染,也就是在构建render树时,等到css下载解析后才进行(与浏览器优化有关,防止css规则不断变化,避免重复的构建)

(3)有例外,遇到media query 声明的css是不会阻塞构建render树

 

(3)遇到js脚本资源

JS脚本资源的处理有几个特点:

(1)阻塞浏览器的解析,也就是说发现一个外链脚本时,需等待脚本下载完成并执行后才会继续解析HTML。

(2)浏览器的优化,一般现代浏览器有优化,在脚本阻塞时,也会继续下载其它资源(当然有并发上限),但是虽然脚本可以并行下载,解析过程仍然是阻塞的,也就是说必须这个脚本执行完毕后才会接下来的解析,并行下载只是一种优化而已。

(3)defer与async,普通的脚本是会阻塞浏览器解析的,但是可以加上defer或async属性,这样脚本就变成异步了,可以等到解析完毕后再执行。

注意,defer和async是有区别的:defer是延迟执行,而async是异步执行。

简单的说:

(1)async是异步执行,异步下载完毕后就会执行,不确保执行顺序,一定在onload前,但不确定在DOMContentLoaded事件的前或后。

(2)defer是延迟执行,在浏览器看起来的效果像是将脚本放在了body后面一样(虽然按规范应该是在DOMContentLoaded事件前,但实际上不同浏览器的优化效果不一样,也有可能在它后面)。

 

(4)遇到img图片类资源

遇到图片等资源时,直接就是异步下载,不会阻塞解析,下载完毕后直接用图片替换原有src的地方

 

9、loaded和domcontentloaded

对比:

(1)DOMContentLoaded 事件触发时,仅当DOM加载完成,不包括样式表,图片(譬如如果有async加载的脚本就不一定完成)。

(2)load 事件触发时,页面上所有的DOM,样式表,脚本,图片都已经加载完成了。

Guess you like

Origin blog.csdn.net/saucxs/article/details/90476340