从Chrome源码看浏览器如何加载资源

系统 浏览器
本篇是研究了三个周末四五天的时间才得到的,而且为了避免错误不会随便进行臆测,基本上每个小点都是实际debug执行和打印console得到的,经过验证了才写出来。

对浏览器加载资源有很多不确定性,例如:

  • css/font的资源的优化级会比img高,资源的优化级是怎么确定的呢?
  • 资源优先级又是如何影响加载的先后顺序的?
  • 有几种情况可能会导致资源被阻止加载?

通过源码可以找到答案。此次源码解读基于Chromium 64(10月28日更新的源码)。

下面通过加载资源的步骤,依次说明。

1. 开始加载

通过以下命令打开Chromium,同时打开一个网页:

  1. chromium --renderer-startup-dialog https://www.baidu.com 

Chrome会在DocumentLoader.cpp里面通过以下代码去加载:

  1. enum Type : uint8_t { 
  2.     kMainResource, 
  3.     kImage, 
  4.     kCSSStyleSheet, 
  5.     kScript, 
  6.     kFont, 
  7.     kRaw, 
  8.     kSVGDocument, 
  9.     kXSLStyleSheet, 
  10.     kLinkPrefetch, 
  11.     kTextTrack, 
  12.     kImportResource, 
  13.     kMedia,  // Audio or video file requested by a HTML5 media element 
  14.     kManifest, 
  15.     kMock  // Only for testing 
  16.   }; 

除了常见的image/css/js/font之外,我们发现还有像textTrack的资源,这个是什么东西呢?这个是video的字幕,使用webvtt格式:

  1. <video controls poster="/images/sample.gif"
  2.    <source src="sample.mp4" type="video/mp4"
  3.    <track kind="captions" src="sampleCaptions.vtt" srclang="en"
  4. </video> 

还有动态请求ajax属于Raw类型。因为ajax可以请求多种资源。

MainResource包括location即导航输入地址得到的页面、使用frame/iframe嵌套的、通过超链接点击的页面以及表单提交这几种。

接着交给稍底层的ResourceFecher去加载,所有资源都是通过它加载:

  1. fetcher->RequestResource( 
  2.       params, RawResourceFactory(Resource::kMainResource), substitute_data) 

在这个里面会先对请求做预处理。

2. 预处理请求

每发个请求会生成一个ResourceRequest对象,这个对象包含了http请求的所有信息:

包括url、http header、http body等,还有请求的优先级信息等:

然后会根据页面的加载策略对这个请求做一些预处理,如下代码:

  1. PrepareRequestResult result = PrepareRequest(params, factory, substitute_data, 
  2.                                               identifier, blocked_reason); 
  3.  if (result == kAbort) 
  4.    return nullptr; 
  5.  if (result == kBlock) 
  6.    return ResourceForBlockedRequest(params, factory, blocked_reason); 

prepareRequest会做两件事情,一件是检查请求是否合法,第二件是把请求做些修改。如果检查合法性返回kAbort或者kBlock,说明资源被废弃了或者被阻止了,就不去加载了。

被block的原因可能有以下几种:

  1. enum class ResourceRequestBlockedReason { 
  2.   kCSP,              // CSP内容安全策略检查 
  3.   kMixedContent,     // mixed content 
  4.   kOrigin,           // secure origin 
  5.   kInspector,        // devtools的检查器 
  6.   kSubresourceFilter, 
  7.   kOther, 
  8.   kNone 
  9. }; 

源码里面会在这个函数做合法性检查:

  1. blocked_reason = Context().CanRequest(/*参数省略*/); 
  2.  if (blocked_reason != ResourceRequestBlockedReason::kNone) { 
  3.    return kBlock; 
  4.  } 

CanRequest函数会相应地检查以下内容:

(1)CSP(Content Security Policy)内容安全策略检查

CSP是减少XSS攻击一个策略。如果我们只允许加载自己域的图片的话,可以加上下面这个meta标签:

  1. <meta http-equiv="Content-Security-Policy" content="img-src 'self';"

或者是后端设置这个http响应头。

self表示本域,如果加载其它域的图片浏览器将会报错:

所以这个可以防止一些XSS注入的跨域请求。

源码里面会检查该请求是否符合CSP的设定要求:

  1. const ContentSecurityPolicy* csp = GetContentSecurityPolicy(); 
  2.   if (csp && !csp->AllowRequest( 
  3.                  request_context, url, options.content_security_policy_nonce, 
  4.                  options.integrity_metadata, options.parser_disposition, 
  5.                  redirect_status, reporting_policy, check_header_type)) { 
  6.     return ResourceRequestBlockedReason::kCSP; 
  7.   } 

如果有CSP并且AllowRequest没有通过的话就会返回堵塞的原因。具体的检查过程是根据不同的资源类型去获取该类资源资源的CSP设定进行比较。

接着会根据CSP的要求改变请求:

  1. ModifyRequestForCSP(request); 

主要是升级http为https。

(2)upgrade-insecure-requests

如果设定了以下CSP规则:

  1. <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"

那么会将网页的http请求强制升级为https,这是通过改变request对象实现的:

  1. url.SetProtocol("https"); 
  2.       if (url.Port() == 80) 
  3.         url.SetPort(443); 
  4.       resource_request.SetURL(url); 

包括改变url的协议和端口号。

(3)Mixed Content混合内容block

在https的网站请求http的内容就是Mixed Content,例如加载一个http的JS脚本,这种请求通常会被浏览器堵塞掉,因为http是没有加密的,容易受到中间人的攻击,如修改JS的内容,从而控制整个https的页面,而图片之类的资源即使内容被修改可能只是展示出问题,所以默认没有block掉。源码里面会检查Mixed Content的内容:

  1. if (ShouldBlockFetchByMixedContentCheck(request_context, frame_type, 
  2.                                           resource_request.GetRedirectStatus(), 
  3.                                           url, reporting_policy)) 
  4.     return ResourceRequestBlockedReason::kMixedContent; 

在源码里面,以下4种资源是optionally-blockable(被动混合内容):

  1. // "Optionally-blockable" mixed content 
  2.    case WebURLRequest::kRequestContextAudio: 
  3.    case WebURLRequest::kRequestContextFavicon: 
  4.    case WebURLRequest::kRequestContextImage: 
  5.    case WebURLRequest::kRequestContextVideo: 
  6.      return WebMixedContentContextType::kOptionallyBlockable; 

什么叫被动混合内容呢?W3C文档是这么说的:那些不会打破页面重要部分,风险比较低的,但是使用频率又比较高的Mixed Content内容。

而剩下的其它所有资源几乎都是blockable的,包括JS/CSS/Iframe/XMLHttpRequest等:

我们注意到img srcset里的资源也是默认会被阻止的,即下面的img会被block:

  1. <img srcset="http://fedren.com/test-1x.png 1x, http://fedren.com/test-2x.png 2x" alt> 

但是使用src的不会被block:

  1. <img src="http://fedren.com/images/sell/icon-home.png" alt> 

如下图所示:

这就是optionally-blockable和blocakable资源的区分。

对于被动混合内容,如果设置strick mode:

  1. <meta http-equiv="Content-Security-Policy" content="block-all-mixed-content"

那么即使是optionally的也会被block掉:

  1. case WebMixedContentContextType::kOptionallyBlockable: 
  2.       allowed = !strict_mode; 
  3.       if (allowed) { 
  4.         content_settings_client->PassiveInsecureContentFound(url); 
  5.         client->DidDisplayInsecureContent(); 
  6.       } 
  7.       break; 

上面代码,如果strick_mode是true,allowed就是false,被动混合内容就会被阻止。

而对于主动混合内容,如果用户设置允许加载:

 

那么也是可以加载的:

  1. case WebMixedContentContextType::kBlockable: { 
  2.      // Strictly block subresources that are mixed with respect to their 
  3.      // subframes, unless all insecure content is allowed. This is to avoid the 
  4.      // following situation: https://a.com embeds https://b.com, which loads a 
  5.      // script over insecure HTTP. The user opts to allow the insecure content, 
  6.      // thinking that they are allowing an insecure script to run on 
  7.      // https://a.com and not realizing that they are in fact allowing an 
  8.      // insecure script on https://b.com. 
  9.  
  10.      bool should_ask_embedder = 
  11.          !strict_mode && settings && 
  12.          (!settings->GetStrictlyBlockBlockableMixedContent() || 
  13.           settings->GetAllowRunningOfInsecureContent()); 
  14.      allowed = should_ask_embedder && 
  15.                content_settings_client->AllowRunningInsecureContent( 
  16.                    settings && settings->GetAllowRunningOfInsecureContent(), 
  17.                    security_origin, url); 
  18.      break; 

代码倒数第4行会去判断当前的client即当前页面的设置是否允许加载blockable的资源。另外源码注释还提到了一种特殊的情况,就是a.com的页面包含了b.com的页面,b.com允许加载blockable的资源,a.com在非strick mode的时候页面是允许加载的,但是如果a.com是strick mode,那么将不允许加载。

并且如果页面设置了strick mode,用户设置的允许blockable资源加载的设置将会失效:

  1. // If we're in strict mode, we'll automagically fail everything, and 
  2.  // intentionally skip the client checks in order to prevent degrading the 
  3.  // site's security UI. 
  4.  bool strict_mode = 
  5.      mixed_frame->GetSecurityContext()->GetInsecureRequestPolicy() & 
  6.          kBlockAllMixedContent || 
  7.      settings->GetStrictMixedContentChecking(); 

这个主要是svg使用use的获取svg资源的时候必须不能跨域,如下以下资源将会被阻塞:

  1. <svg> 
  2.     <use href="http://cdn.test.com/images/logo.svg#abc"></use> 
  3. </svg> 

如下图所示:

并且控制台会打印:

源码里面会对这种use link加载的svg做一个检验:

  1. case Resource::kSVGDocument: 
  2.       if (!security_origin->CanRequest(url)) { 
  3.         PrintAccessDeniedMessage(url); 
  4.         return ResourceRequestBlockedReason::kOrigin; 
  5.       } 
  6.       break; 

具体检验CanRequest函数主要是检查是否同源:

  1. // We call isSameSchemeHostPort here instead of canAccess because we want 
  2.   // to ignore document.domain effects. 
  3.   if (IsSameSchemeHostPort(target_origin.get())) 
  4.     return true
  5.   
  6.   return false

如果协议、域名、端口号都一样则通过检查。需要这里和同源策略是两码事,这里的源阻塞是连请求都发不出去,而同源策略只是阻塞请求的返回结果。

svg的use外链一般是用来做svg的雪碧图的,但是为什么需要同源呢,如果不同源会有什么不安全的因素?这里我也不清楚,暂时没查到,W3C只是说明了需要同源,但没有给出原因。

以上就是3种主要的block的原因。在预处理请求里面除了判断资源有没有被block或者abort(abort的原因通常是url不合法),还会计算资源的加载优先级。

3. 资源优先级

(1)计算资源加载优先级

通过调用以下函数设定:

  1. resource_request.SetPriority(ComputeLoadPriority( 
  2.      resource_type, params.GetResourceRequest(), ResourcePriority::kNotVisible, 
  3.      params.Defer(), params.GetSpeculativePreloadType(), 
  4.      params.IsLinkPreload())); 

我们来看一下这个函数里面是怎么计算当前资源的优先级的。

首先每个资源都有一个默认的优先级,这个优先级做为初始化值

  1. ResourceLoadPriority priority = TypeToPriority(type); 

不同类型的资源优先级是这么定义的:

  1. ResourceLoadPriority TypeToPriority(Resource::Type type) { 
  2.   switch (type) { 
  3.     case Resource::kMainResource: 
  4.     case Resource::kCSSStyleSheet: 
  5.     case Resource::kFont: 
  6.       // Also parser-blocking scripts (set explicitly in loadPriority) 
  7.       return kResourceLoadPriorityVeryHigh; 
  8.     case Resource::kXSLStyleSheet: 
  9.       DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); 
  10.     case Resource::kRaw: 
  11.     case Resource::kImportResource: 
  12.     case Resource::kScript: 
  13.       // Also visible resources/images (set explicitly in loadPriority) 
  14.       return kResourceLoadPriorityHigh; 
  15.     case Resource::kManifest: 
  16.     case Resource::kMock: 
  17.       // Also late-body scripts discovered by the preload scanner (set 
  18.       // explicitly in loadPriority) 
  19.       return kResourceLoadPriorityMedium; 
  20.     case Resource::kImage: 
  21.     case Resource::kTextTrack: 
  22.     case Resource::kMedia: 
  23.     case Resource::kSVGDocument: 
  24.       // Also async scripts (set explicitly in loadPriority) 
  25.       return kResourceLoadPriorityLow; 
  26.     case Resource::kLinkPrefetch: 
  27.       return kResourceLoadPriorityVeryLow; 
  28.   } 
  29.   
  30.   return kResourceLoadPriorityUnresolved; 

可以看到优先级总共分为五级:very-high、high、medium、low、very-low,其中MainRescource页面、CSS、字体这三个的优先级是最高的,然后就是Script、Ajax这种,而图片、音视频的默认优先级是比较低的,最低的是prefetch预加载的资源。

什么是prefetch的资源呢?有时候你可能需要让一些资源先加载好等着用,例如用户输入出错的时候在输入框右边显示一个X的图片,如果等要显示的时候再去加载就会有延时,这个时候可以用一个link标签:

  1. <link rel="prefetch" href="image.png"

浏览器空闲的时候就会去加载。另外还可以预解析DNS:

  1. <link rel="dns-prefetch" href="https://cdn.test.com"

预建立TCP连接:  

  1. <link rel="preconnect" href="https://cdn.chime.me"

后面这两个不属于加载资源,这里顺便提一下。

注意上面的switch-case设定资源优先级有一个顺序,如果既是script又是prefetch的话得到的优化级是high,而不是prefetch的very low,因为prefetch是最后一个判断。所以在设定了资源默认的优先级之后,会再对一些情况做一些调整,主要是对prefetch/preload的资源。包括:

a)降低preload的字体的优先级

如下代码:

  1. // A preloaded font should not take precedence over critical CSS or 
  2.   // parser-blocking scripts. 
  3.   if (type == Resource::kFont && is_link_preload) 
  4.     priority = kResourceLoadPriorityHigh; 

会把预加载字体的优先级从very-high变成high

b)降低defer/async的script的优先级

如下代码:

  1. if (type == Resource::kScript) { 
  2.     // Async/Defer: Low Priority (applies to both preload and parser-inserted) 
  3.     if (FetchParameters::kLazyLoad == defer_option) { 
  4.       priority = kResourceLoadPriorityLow; 
  5.     } 

script如果是defer的话,那么它优先级会变成最低。

4)页面底部preload的script优先级变成medium

如下代码:

  1. if (type == Resource::kScript) { 
  2.     // Special handling for scripts. 
  3.     // Default/Parser-Blocking/Preload early in document: High (set in 
  4.     // typeToPriority) 
  5.     // Async/Defer: Low Priority (applies to both preload and parser-inserted) 
  6.     // Preload late in document: Medium 
  7.     if (FetchParameters::kLazyLoad == defer_option) { 
  8.       priority = kResourceLoadPriorityLow; 
  9.     } else if (speculative_preload_type == 
  10.                    FetchParameters::SpeculativePreloadType::kInDocument && 
  11.                image_fetched_) { 
  12.       // Speculative preload is used as a signal for scripts at the bottom of 
  13.       // the document. 
  14.       priority = kResourceLoadPriorityMedium; 
  15.     } 

如果是defer的script那么优先级调成最低(上面第3小点),否则如果是preload的script,并且如果页面已经加载了一张图片就认为这个script是在页面偏底部的位置,就把它的优先级调成medium。通过一个flag决定是否已经加载过第一张图片了:

  1. // Resources before the first image are considered "early" in the document and 
  2.   // resources after the first image are "late" in the document.  Important to 
  3.   // note that this is based on when the preload scanner discovers a resource 
  4.   // for the most part so the main parser may not have reached the image element 
  5.   // yet. 
  6.   if (type == Resource::kImage && !is_link_preload) 
  7.     image_fetched_ = true

资源在第一张非preload的图片前认为是early,而在后面认为是late,late的script的优先级会偏低。

什么叫preload呢?preload不同于prefetch的,在早期浏览器,script资源是阻塞加载的,当页面遇到一个script,那么要等这个script下载和执行完了,才会继续解析剩下的DOM结构,也就是说script是串行加载的,并且会堵塞页面其它资源的加载,这样会导致页面整体的加载速度很慢,所以早在2008年的时候浏览器出了一个推测加载(speculative preload)策略,即遇到script的时候,DOM会停止构建,但是会继续去搜索页面需要加载的资源,如看下后续的html有没有img/script标签,先进行预加载,而不用等到构建DOM的时候才去加载。这样大大提高了页面整体的加载速度。

5)把同步即堵塞加载的资源的优先级调成最高

如下代码:

  1. // A manually set priority acts as a floor. This is used to ensure that 
  2.  // synchronous requests are always given the highest possible priority 
  3.  return std::max(priority, resource_request.Priority()); 

如果是同步加载的资源,那么它的request对象里面的优先最级是最高的,所以本来是hight的ajax同步请求在最后return的时候会变成very-high。

这里是取了两个值的最大值,第一个值是上面进行各种判断得到的priority,第二个在初始这个ResourceRequest对象本身就有的一个优先级属性,返回最大值后再重新设置resource_request的优先级属性。

在构建resource request对象时所有资源都是最低的,这个可以从构造函数里面知道:

  1. ResourceRequest::ResourceRequest(const KURL& url) 
  2.     : url_(url), 
  3.       service_worker_mode_(WebURLRequest::ServiceWorkerMode::kAll), 
  4.       priority_(kResourceLoadPriorityLowest) 
  5.       /* 其它参数略 */ {} 

但是同步请求在初始化的时候会先设置成最高:

  1. void FetchParameters::MakeSynchronous() { 
  2.   // Synchronous requests should always be max priority, lest they hang the 
  3.   // renderer. 
  4.   resource_request_.SetPriority(kResourceLoadPriorityHighest); 
  5.   resource_request_.SetTimeoutInterval(10); 
  6.   options_.synchronous_policy = kRequestSynchronously; 

以上就是基本的资源加载优先级策略。

(2)转换成Net的优先级

这个是在渲染线程里面进行的,上面提到的资源优先级在发请求之前会被转化成Net的优先级:

  1. resource_request->priority = 
  2.       ConvertWebKitPriorityToNetPriority(request.GetPriority()); 

资源优先级对应Net的优先级关系如下所示:

画成一个表:

Net Priority是请求资源的时候使用的,这个是在Chrome的IO线程里面进行的, 我在《JS与多线程》的Chrome的多线程模型里面提到,每个页面都有Renderer线程负责渲染页面,而浏览器有IO线程,用来负责请求资源等。为什么IO线程不是放在每个页面里面而是放在浏览器框架呢?因为这样的好处是如果两个页面请求了相同资源的话,如果有缓存的话就能避免重复请求了。

上面的都是在渲染线程里面debug操作得到的数据,为了能够观察资源请求的过程,需要切换到IO线程,而这两个线程间的通信是通过Chrome封装的Mojo框架进行的。在Renderer线程会发一个消息给IO线程通知它:

  1. mojo::Message message( 
  2.       internal::kURLLoaderFactory_CreateLoaderAndStart_Name, kFlags, 0, 0, nullptr); 
  3.  // 对这个message进行各种设置后(代码略),调接收者的Accept函数  
  4.  ignore_result(receiver_->Accept(&message)); 

XCode里面可以看到这是在渲染线程RendererMain里操作的:

 

现在要切到Chrome的IO线程,把debug的方式改一下,如下选择Chromium程序:

 

之前是使用Attach to Process把渲染进程的PID传进来,因为每个页面都是独立的一个进程,现在要改成debug Chromium进程。然后在content/browser/loader/resource_scheduler.cc这个文件里的ShouldStartRequest函数里面打个断点,接着在Chromium里面打开一个网页,就可以看到断点生效了。在XCode里面可以看到当前线程名称叫Chrome_IOThread:

这与上面的描述一致。IO线程是如何利用优先级决定要不要开始加载资源的呢?

(3)资源加载

上面提到的ShouldStartRequest这个函数是判断当前资源是否能开始加载了,如果能的话就准备加载了,如果不能的话就继续把它放到pending request队列里面,如下代码所示:

  1. void ScheduleRequest(const net::URLRequest& url_request, 
  2.                       ScheduledResourceRequest* request) { 
  3.    SetRequestAttributes(request, DetermineRequestAttributes(request)); 
  4.    ShouldStartReqResult should_start = ShouldStartRequest(request); 
  5.    if (should_start == START_REQUEST) { 
  6.      // New requests can be started synchronously without issue. 
  7.      StartRequest(request, START_SYNC, RequestStartTrigger::NONE); 
  8.    } else { 
  9.      pending_requests_.Insert(request); 
  10.    } 
  11.  } 

一旦收到Mojo的加载资源消息就会调上面的ScheduleRequest函数,除了收到消息之外,还有一个地方也会调用:

  1. void LoadAnyStartablePendingRequests(RequestStartTrigger trigger) { 
  2.    // We iterate through all the pending requests, starting with the highest 
  3.    // priority one.  
  4.    RequestQueue::NetQueue::iterator request_iter = 
  5.        pending_requests_.GetNextHighestIterator(); 
  6.  
  7.    while (request_iter != pending_requests_.End()) { 
  8.      ScheduledResourceRequest* request = *request_iter; 
  9.      ShouldStartReqResult query_result = ShouldStartRequest(request); 
  10.  
  11.      if (query_result == START_REQUEST) { 
  12.        pending_requests_.Erase(request); 
  13.        StartRequest(request, START_ASYNC, trigger); 
  14.      } 
  15.  } 

这个函数的特点是遍历pending requests,每次取出优先级最高的一个request,然后调ShouldStartRequest判断是否能运行了,如果能的话就把它从pending requests里面删掉,然后运行。

而这个函数会有三个地方会调用,一个是IO线程的循环判断,只要还有未完成的任务,就会触发加载,第二个是当有请求完成时会调,第三个是要插入body标签的时候。所以主要总共有三个地方会触发加载:

(1)收到来自渲染线程IPC::Mojo的请求加载资源的消息

(2)每个请求完成之后,触发加载pending requests里还未加载的请求

(3)IO线程定时循环未完成的任务,触发加载

  1. <!DOCType html> 
  2. <html> 
  3. <head> 
  4.     <meta charset="utf-8"
  5.     <link rel="icon" href="4.png"
  6.     <img src="0.png"
  7.     <img src="1.png"
  8.     <link rel="stylesheet" href="1.css"
  9.     <link rel="stylesheet" href="2.css"
  10.     <link rel="stylesheet" href="3.css"
  11.     <link rel="stylesheet" href="4.css"
  12.     <link rel="stylesheet" href="5.css"
  13.     <link rel="stylesheet" href="6.css"
  14.     <link rel="stylesheet" href="7.css"
  15. </head> 
  16. <body> 
  17.     <p>hello</p> 
  18.     <img src="2.png"
  19.     <img src="3.png"
  20.     <img src="4.png"
  21.     <img src="5.png"
  22.     <img src="6.png"
  23.     <img src="7.png"
  24.     <img src="8.png"
  25.     <img src="9.png"
  26.   
  27.     <script src="1.js"></script> 
  28.     <script src="2.js"></script> 
  29.     <script src="3.js"></script> 
  30.   
  31.     <img src="3.png"
  32. <script> 
  33. !function(){ 
  34.     let xhr = new XMLHttpRequest(); 
  35.     xhr.open("GET""https://baidu.com"); 
  36.     xhr.send(); 
  37.     document.write("hi"); 
  38. }(); 
  39. </script> 
  40. <link rel="stylesheet" href="9.css"
  41. </body> 
  42. </html> 

知道了触发加载机制之的,接着研究具体优先加载的过程,用以下html做为demo:

然后把Chrome的网络速度调为Fast 3G,让加载速度降低,以便更好地观察这个过程,结果如下图所示:

从上图可以发现以下特点:

(1)每个域每次最多同时加载6个资源(http/1.1)

(2)CSS具有最高的优先级,最先加载,即使是放在最后面9.css也是比前面资源先开始加载

(3)JS比图片优先加载,即使出现得比图片晚

(4)只有等CSS都加载完了,才能加载其它的资源,即使这个时候没有达到6个的限制

(5)head里面的非高优化级的资源最多能先加载一张(0.png)

(6)xhr的资源虽然具有高优先级,但是由于它是排在3.js后面的,JS的执行是同步的,所以它排得比较靠后,如果把它排在1.js前面,那么它也会比图片先加载。

为什么是这样呢?我们从源码寻找答案。

首先认清几个概念,请求可分为delayable和none-delayable两种:

  1. // The priority level below which resources are considered to be delayable. 
  2. static const net::RequestPriority 
  3.     kDelayablePriorityThreshold = net::MEDIUM; 

在优先级在Medium以下的为delayable,即可推迟的,而大于等于Medium的为不可delayable的。从刚刚我们总结的表可以看出:css/js是不可推迟的,而图片、preload的js为可推迟加载:

还有一种是layout-blocking的请求:

  1. // The priority level above which resources are considered layout-blocking if 
  2. // the html_body has not started. 
  3. static const net::RequestPriority 
  4.     kLayoutBlockingPriorityThreshold = net::MEDIUM; 

这是当还没有渲染body标签,并且优先级在Medium之上的如CSS的请求。

然后,上面提到的ShouldStartRequest函数,这个函数是规划资源加载顺序最主要的函数,从源码注释可以知道它大概的过程:

  1. // ShouldStartRequest is the main scheduling algorithm. 
  2.   // 
  3.   // Requests are evaluated on five attributes: 
  4.   // 
  5.   // 1. Non-delayable requests: 
  6.   //   * Synchronous requests. 
  7.   //   * Non-HTTP[S] requests. 
  8.   // 
  9.   // 2. Requests to request-priority-capable origin servers. 
  10.   // 
  11.   // 3. High-priority requests: 
  12.   //   * Higher priority requests (> net::LOW). 
  13.   // 
  14.   // 4. Layout-blocking requests: 
  15.   //   * High-priority requests (> net::MEDIUM) initiated before the renderer has 
  16.   //     a <body>. 
  17.   // 
  18.   // 5. Low priority requests 
  19.   // 
  20.   //  The following rules are followed: 
  21.   // 
  22.   //  All types of requests: 
  23.   //   * Non-delayable, High-priority and request-priority capable requests are 
  24.   //     issued immediately. 
  25.   //   * Low priority requests are delayable. 
  26.   //   * While kInFlightNonDelayableRequestCountPerClientThreshold(=1) 
  27.   //     layout-blocking requests are loading or the body tag has not yet been 
  28.   //     parsed, limit the number of delayable requests that may be in flight 
  29.   //     to kMaxNumDelayableWhileLayoutBlockingPerClient(=1). 
  30.   //   * If no high priority or layout-blocking requests are in flight, start 
  31.   //     loading delayable requests. 
  32.   //   * Never exceed 10 delayable requests in flight per client. 
  33.   //   * Never exceed 6 delayable requests for a given host. 

从上面的注释可以得到以下信息:

(1)高优先级的资源(>=Medium)、同步请求和非http(s)的请求能够立刻加载

(2)只要有一个layout blocking的资源在加载,最多只能加载一个delayable的资源,这个就解释了为什么0.png能够先加载

(3)只有当layout blocking和high priority的资源加载完了,才能开始加载delayable的资源,这个就解释了为什么要等CSS加载完了才能加载其它的js/图片。

(4)同时加载的delayable资源同一个域只能有6个,同一个client即同一个页面最多只能有10个,否则要进行排队。

注意这里说的开始加载,并不是说能够开始请求建立连接了。源码里面叫in flight,在飞行中,而不是叫in request之类的,能够进行in flight的请求是指那些不用queue的请求,如下图:

 

白色条是指queue的时间段,而灰色的是已经in flight了但受到同域只能最多只能建立6个TCP连接等的影响而进入的stalled状态,绿色是TTFB(Time to First Byte)从开始建立TCP连接到收到第一个字节的时间,蓝色是下载的时间。

我们已经解释了大部分加载的特点的原因,对着上面那张图可以再重述一次:

(1)由于1.css到9.css这几个CSS文件是high priority或者是none delayable的,所以马上in flight,但是还受到了同一个域最多只能有6个的限制,所以6/7/9.css这三个进入stalled的状态

(2)1.css到5.css是layout-blocking的,所以最多只能再加载一个delayable的0.png,在它相邻的1.png就得排队了

(3)等到high priority和layout-blocking的资源7.css/9.css/1.js加载完了,就开始加载delayable的资源,主要是preload的js和图片

这里有个问题,为什么1.js是high priority的而2.js和3.js却是delayable的?为此在源码的ShouldStartRequest函数里面添加一些代码,把每次判断请求的一些关键信息打印出来:

  1. LOG(INFO) << "url: " << url_request.url().spec() << " priority: " << url_request.priority() 
  2.     << " has_html_body_: " << has_html_body_ << " delayable: " 
  3.     << RequestAttributesAreSet(request->attributes(), kAttributeDelayable); 

把打印出来的信息按顺序画成以下表格:

1.js的优先级一开始是Low的,即是delayable的,但是后面又变成了Medium就不是delayable了,是high priority,为什么它的优先级能够提高呢?一开始是Low是因为它是推测加载的,所以是优先级比较低,但是当DOM构建到那里的时候它就不是preload的,变成正常的JS加载了,所以它的优先级变成了Medium,这个可以从has_html_body标签进行推测,而2.js要等到1.js下载和解析完,它能算是正常加载,否则还是推测加载,因此它的优先级没有得到提高。

本次解读到这里告一段落,我们得到了有3种原因会阻止加载资源,包括CSP、Mixed Content、Origin block,CSP是自己手动设置的一些限制,Mixed Content是https页面不允许加载http的内容,Origin Block主要是svg的href只能是同源的资源。还知道了浏览器把资源归成CSS/Font/JS/Image等几类,总共有5种优先级,从Lowest到Highest,每种资源都会设定一个优先级,总的来说CSS/Font/Frame和同步请求这四种的优先级是最高的,不能推迟加载的,而正常加载的JS属于高优先级,推测加载preload则优先级会比较低,会推迟加载。并且如果有layout blocking的请求的话,那么delayable的资源要等到高优先级的加载完了才能进行加载。已经开始加载的资源还可能会处于stalled的状态,因为每个域同时建立的TCP连接数是有限的。

但是我们还有很多问题没有得到解决,例如:

(1)同源策略具体是怎样处理的?

(2)优先级是如何动态改变的?

(3)http cache/service worker是如何影响资源加载的?

我们将尝试在下一次解读进行回答,看源码是一件比较费时费力的事情,本篇是研究了三个周末四五天的时间才得到的,而且为了避免错误不会随便进行臆测,基本上每个小点都是实际debug执行和打印console得到的,经过验证了才写出来。但是由于看的深度有限和理解偏差,可能会有一些不全面的地方甚至错误,但是从注释可以看到有些地方为什么有这个判断条件即使是源码的维护者也不太确定。本篇解读尽可能地实事求事。

责任编辑:武晓燕 来源: 51CTO专栏
相关推荐

2017-02-28 10:05:56

Chrome源码

2017-02-07 09:44:12

Chrome源码DOM树

2017-02-09 15:15:54

Chrome浏览器

2011-06-21 16:52:48

2012-07-04 17:00:06

猎豹浏览浏览器

2021-01-07 07:52:04

浏览器网页资源加载

2020-05-15 15:23:25

Chrome浏览器谷歌

2010-01-28 10:13:43

2018-02-02 15:48:47

ChromeDNS解析

2009-11-26 10:55:41

2015-01-21 15:45:50

斯巴达浏览器

2021-05-07 13:56:13

Linux器监视服务器

2020-11-25 09:47:11

FedoraGoogle Chro浏览器

2022-02-07 21:49:06

浏览器渲染chromium

2010-01-10 17:50:17

2009-09-22 09:17:46

谷歌Chrome浏览器

2012-08-08 09:18:47

Chrome浏览器

2009-07-17 09:16:20

Google Chro浏览器操作系统

2013-11-13 15:54:20

Chrome 31浏览器

2019-02-15 15:15:59

ChromeJavascriptHtml
点赞
收藏

51CTO技术栈公众号