aboutsummaryrefslogtreecommitdiff
path: root/files/es/web/performance/how_browsers_work/index.html
blob: 95677a1f2dba82d8f7d43da835a592123bcbe241 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
---
title: 'Populating the page: how browsers work'
slug: Web/Performance/How_browsers_work
tags:
  - Composición
  - Navegadorres
  - Renderizado
translation_of: Web/Performance/How_browsers_work
---
<p>Los usuarios quieren que las experiencias en la web sean rápidas y que tengan una intereacción sencilla. Por este motivo, los desarrolladores debén esforzarse para lograr estos dos objetivos</p>

<p>Para entender como mejorar el desempeño, es importante entender como funciona el navegador.</p>

<p>Overview</p>

<p>Fast sites provide better user experiences. Users want and expect web experiences with content that is fast to load and smooth to interact with.</p>

<p>Two major issues in web performance are understanding issues having to do with latency and issues having to do with the fact that for the most part, browsers are single threaded.</p>

<p>Latency is our main threat to overcome to ensure a fast load. To be fast to load, the developers’ goals include sending requested information as fast as possible, or at least seem super fast. Network latency is the time it takes to transmit bytes over-the-air to computers. Web performance is what we have to do to make the page load happen as quickly as possible.</p>

<p>For the most part, browsers are considered single threaded. For smooth interactions, the developer's goal is to ensure performant site interactions, from smooth scrolling to being responsive to touch. Render time is key, with ensuring the main thread can complete all the work we throw at it and still always be available to handle user interactions. Web performance can be improved by understanding the single-threaded nature of the browser and minimizing the main thread's responsibilities, where possible and appropriate, to ensure rendering is smooth and responses to interactions are immediate.</p>

<h2 id="Navigation">Navigation</h2>

<p><em>Navigation</em> is the first step in loading a web page. It occurs whenever a user requests a page by entering a URL into the address bar, clicking a link, submitting a form, as well as other actions.</p>

<p>One of the goals of web performance is to minimize the amount of time a navigation takes to complete. In ideal conditions, this usually doesn't take too long, but latency and bandwidth are foes which can cause delays.</p>

<h3 id="DNS_Lookup">DNS Lookup</h3>

<p>The first step of navigating to a web page is finding where the assets for that page are located. If you navigate to <code>https://example.com</code>, the HTML page is located on the server with IP address of <code>93.184.216.34</code>. If you’ve never visited this site, a DNS lookup must happen.</p>

<p>Your browser requests a DNS lookup, which is eventually fielded by a name server, which in turn responds with an IP address. After this initial request, the IP will likely be cached for a time, which speeds up subsequent requests by retrieving the IP address from the cache instead of contacting a name server again.</p>

<p>DNS lookups usually only need to be done once per hostname for a page load. However, DNS lookups must be done for each unique hostname the requested page references. If your fonts, images, scripts, ads, and metrics all have different hostnames, a DNS lookup will have to be made for each one.</p>

<p><img alt="Mobile requests go first to the cell tower, then to a central phone company computer before being sent to the internet" src="https://mdn.mozillademos.org/files/16743/latency.jpg" style="height: 281px; width: 792px;"></p>

<p>This can be problematic for performance, particularly on mobile networks. When a user is on a mobile network, each DNS lookup has to go from the phone to the cell tower to reach an authoritative DNS server. The distance between a phone, a cell tower, and the name server can add significant latency.</p>

<h3 id="TCP_Handshake">TCP Handshake</h3>

<p>Once the IP address is known, the browser sets up a connection to the server via a {{glossary('TCP handshake','TCP three-way handshake')}}. This mechanism is designed so that two entities attempting to communicate—in this case the browser and web server—can negotiate the parameters of the network TCP socket connection before transmitting data, often over {{glossary('HTTPS')}}.</p>

<p>TCP's three way handshaking technique is often referred to as "SYN-SYN-ACK"—or more accurately SYN, SYN-ACK, ACK—because there are three messages transmitted by TCP to negotiate and start a TCP session between two computers. Yes, this means three more messages back and forth between each server, and the request has yet to be made.</p>

<h3 id="TLS_Negotiation">TLS Negotiation</h3>

<p>For secure connections established over HTTPS, another "handshake" is required. This handshake, or rather the {{glossary('TLS')}} negotiation, determines which cipher will be used to encrypt the communication, verifies the server, and establishes that a secure connection is in place before beginning the actual transfer of data. This requires three more round trips to the server before the request for content is actually sent.</p>

<p><img alt="The DNS lookup, the TCP handshake, and 5 steps of the TLS handshake including clienthello, serverhello and certificate, clientkey and finished for both server and client." src="https://mdn.mozillademos.org/files/16746/ssl.jpg" style="height: 412px; width: 729px;"></p>

<p>While making the connection secure adds time to the page load, a secure connection is worth the latency expense, as the data transmitted between the browser and the web server cannot be decrypted by a third party.</p>

<p>After the 8 round trips, the browser is finally able to make the request.</p>

<h2 id="Response">Response</h2>

<p>Once we have an established connection to a web server, the browser sends an initial <a href="/en-US/docs/Web/HTTP/Methods">HTTP <code>GET</code> request</a> on behalf of the user, which for websites is most often an HTML file. Once the server receives the request, it will reply with relevant response headers and the contents of the HTML.</p>

<pre class="brush: html notranslate">&lt;!doctype HTML&gt;
&lt;html&gt;
 &lt;head&gt;
  &lt;meta charset="UTF-8"/&gt;
  &lt;title&gt;My simple page&lt;/title&gt;
  &lt;link rel="stylesheet" src="styles.css"/&gt;
  &lt;script src="myscript.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h1 class="heading"&gt;My Page&lt;/h1&gt;
  &lt;p&gt;A paragraph with a &lt;a href="https://example.com/about"&gt;link&lt;/a&gt;&lt;/p&gt;
  &lt;div&gt;
    &lt;img src="myimage.jpg" alt="image description"/&gt;
  &lt;/div&gt;
  &lt;script src="anotherscript.js"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>

<p>This response for this initial request contains the first byte of data received. {{glossary('Time to First Byte')}} (TTFB) is the time between when the user made the request—say by clicking on a link—and the receipt of this first packet of HTML. The first chunk of content is usually 14kb of data.</p>

<p>In our example above, the request is definitely less than 14Kb, but the linked resources aren't requested until the browser encounters the links during parsing, described below.</p>

<h3 id="TCP_Slow_Start_14kb_rule">TCP Slow Start / 14kb rule</h3>

<p>The first response packet will be 14Kb. This is part of {{glossary('TCP slow start')}}, an algorithm which balances the speed of a network connection. Slow start gradually increases the amount of data transmitted until the network's maximum bandwidth can be determined.</p>

<p>In {{glossary('TCP slow start')}}, after receipt of the initial packet, the server doubles the size of the next packet to around 28Kb. Subsequent packets increase in size until a predetermined threshold is reached, or congestion is experienced.</p>

<p><img alt="TCP slow start" src="https://mdn.mozillademos.org/files/16754/congestioncontrol.jpg" style="height: 412px; width: 729px;"></p>

<p>If you’ve ever heard of the 14Kb rule for initial page load, TCP slow start is the reason why the initial response is 14Kb, and why web performance optimization calls for focusing optimizations with this initial 14Kb response in mind. TCP slow start gradually builds up transmission speeds appropriate for the network's capabilities to avoid congestion.</p>

<h3 id="Congestion_control">Congestion control</h3>

<p><span style="font-weight: 400;">As the server sends data in TCP packets, the user's client confirms delivery by returning acknowledgements, or ACKs. The connection has a limited capacity depending on hardware and network conditions. If the server sends too many packets too quickly, they will be dropped. Meaning, there will be no acknowledgement. The server registers this as missing ACKs. Congestion control algorithms use this flow of sent packets and ACKs to determine a send rate.</span></p>

<h2 id="Parsing">Parsing</h2>

<p>Once the browser receives the first chunk of data, it can begin parsing the information received. {{glossary('speculative parsing', 'Parsing')}} is the step the browser takes to turn the data it receives over the network into the {{glossary('DOM')}} and {{glossary('CSSOM')}}, which is used by the renderer to paint a page to the screen.</p>

<p>The DOM is the internal representation of the markup for the browser. The DOM is also exposed, and can be manipulated through various APIs in JavaScript.</p>

<p>Even if the request page's HTML is larger than the initial 14KB packet, the browser will begin parsing and attempting to render an experience based on the data it has. This is why it's important for web performance optimization to include everything the browser needs to start rendering a page, or at least a template of the page - the CSS and HTML needed for the first render -- in the first 14 kilobytes. But before anything is rendered to the screen, the HTML, CSS, and JavaScript have to be parsed.</p>

<h3 id="Building_the_DOM_tree">Building the DOM tree</h3>

<p>We describe five steps in the <a href="/en-US/docs/Web/Performance/Critical_rendering_path">critical rendering path</a>.</p>

<p>The first step is processing the HTML markup and building the DOM tree. HTML parsing involves <a href="/en-US/docs/Web/API/DOMTokenList">tokenization</a> and tree construction. HTML tokens include start and end tags, as well as attribute names and values. If the document is well-formed, parsing it is straightforward and faster. The parser parses tokenized input into the document, building up the document tree.</p>

<p>The DOM tree describes the content of the document. The <code><a href="/en-US/docs/Web/HTML/Element/html">&lt;html&gt;</a></code> element is the first tag and root node of the document tree. The tree reflects the relationships and hierarchies between different tags. Tags nested within other tags are child nodes. The greater the number of DOM nodes, the longer it takes to construct the DOM tree.</p>

<p><img alt="The DOM tree for our sample code, showing all the nodes, including text nodes." src="https://mdn.mozillademos.org/files/16759/DOM.gif" style="height: 689px; width: 754px;"></p>

<p>When the parser finds non-blocking resources, such as an image, the browser will request those resources and continue parsing. Parsing can continue when a CSS file is encountered, but <code>&lt;script&gt;</code> tags—particularly those without an <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async</a></code> or <code>defer</code> attribute—block rendering, and pause the parsing of HTML. Though the browser's preload scanner hastens this process, excessive scripts can still be a significant bottleneck.</p>

<h3 id="Preload_scanner">Preload scanner</h3>

<p>While the browser builds the DOM tree, this process occupies the main thread. As this happens, the <em>preload scanner</em> will parse through the content available and request high priority resources like CSS, JavaScript, and web fonts. Thanks to the preload scanner, we don't have to wait until the parser finds a reference to an external resource to request it. It will retrieve resources in the background so that by the time the main HTML parser reaches requested assets, they may possibly already be in flight, or have been downloaded. The optimizations the preload scanner provides reduce blockages.</p>

<pre class="brush:html notranslate">&lt;link rel="stylesheet" src="styles.css"/&gt;
&lt;script src="myscript.js" <strong>async</strong>&gt;&lt;/script&gt;
&lt;img src="myimage.jpg" alt="image description"/&gt;
&lt;script src="anotherscript.js" <strong>async</strong>&gt;&lt;/script&gt;
</pre>

<p>In this example, while the main thread is parsing the HTML and CSS, the preload scanner will find the scripts and image, and start downloading them as well. To ensure the script doesn't block the process, add the <code>async</code> attribute, or the <code>defer</code> attribute if JavaScript parsing and execution order is not important.</p>

<p>Waiting to obtain CSS doesn't block HTML parsing or downloading, but it does block JavaScript, because JavaScript is often used to query CSS properties’ impact on elements.</p>

<h3 id="Building_the_CSSOM">Building the CSSOM</h3>

<p>The second step in the critical rendering path is processing CSS and building the CSSOM tree. The CSS object model is similar to the DOM. <span style="color: #212121; display: inline !important; float: none; font-family: Roboto,sans-serif; font-size: 16px; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;">The DOM and CSSOM are both trees. They are independent data structures</span>. The browser converts the CSS rules into a map of styles it can understand and work with. The browser goes through each rule set in the CSS, creating a tree of nodes with parent, child, and sibling relationships based on the CSS selectors.</p>

<p>As with HTML, the browser needs to convert the received CSS rules into something it can work with. Hence, it repeats the HTML-to-object process, but for the CSS.</p>

<p>The CSSOM tree includes styles from the user agent style sheet. The browser begins with the most general rule applicable to a node and recursively refines the computed styles by applying more specific rules. In other words, it cascades the property values.</p>

<p>Building the CSSOM is very, very fast and is not displayed in a unique color in current developer tools. Rather, the "Recalculate Style" in developer tools shows the total time it takes to parse CSS, construct the CSSOM tree, and recursively calculate computed styles. In terms of web performance optimization, there are lower hanging fruit, as the total time to create the CSSOM is generally less than the time it takes for one DNS lookup.</p>

<h3 id="Other_Processes">Other Processes</h3>

<h4 id="JavaScript_Compilation">JavaScript Compilation</h4>

<p>While the CSS is being parsed and the CSSOM created, other assets, including JavaScript files, are downloading (thanks to the preload scanner). JavaScript is interpreted, compiled, parsed and executed. The scripts are parsed into abstract syntax trees. Some browser engines take the {{glossary('Abstract Syntax Tree')}} and pass it into an interpreter, outputting bytecode which is executed on the main thread. This is known as JavaScript compilation.</p>

<h4 id="Building_the_Accessibility_Tree">Building the Accessibility Tree</h4>

<p>The browser also builds an <a href="/en-US/docs/Learn/Accessibility">accessibility</a> tree that assistive devices use to parse and interpret content. The accessibility object model (AOM) is like a semantic version of the DOM. The browser updates the accessibility tree when the DOM is updated. The accessibility tree is not modifiable by assistive technologies themselves.</p>

<p>Until the AOM is built, the content is not accessible to <a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide">screen readers</a>.</p>

<h2 id="Render">Render</h2>

<p>Rendering steps include style, layout, paint and, in some cases, compositing. The CSSOM and DOM trees created in the parsing step are combined into a render tree which is then used to compute the layout of every visible element, which is then painted to the screen. In some cases, content can be promoted to their own layers and composited, improving performance by painting portions of the screen on the GPU instead of the CPU, freeing up the main thread.</p>

<h3 id="Style">Style</h3>

<p>The third step in the critical rendering path is combining the DOM and CSSOM into a render tree.The computed style tree, or render tree, construction starts with the root of the DOM tree, traversing each visible node.</p>

<p>Tags that aren't going to be displayed, like the <code><a href="/en-US/docs/Web/HTML/Element/head">&lt;head&gt;</a></code> and its children and any nodes with <code>display: none</code>, such as the <code>script { display: none; }</code> you will find in user agent stylesheets, are not included in the render tree as they will not appear in the rendered output. Nodes with <code>visibility: hidden</code> applied are included in the render tree, as they do take up space. As we have not given any directives to override the user agent default, the <code>script</code> node in our code example above will not be included in the render tree.</p>

<p>Each visible node has its CSSOM rules applied to it. The render tree holds all the visible nodes with content and computed styles -- matching up all the relevant styles to every visible node in the DOM tree, and determining, based on the <a href="/en-US/docs/Web/CSS/Cascade">CSS cascade</a>, what the computed styles are for each node.</p>

<h3 id="Layout">Layout</h3>

<p>The fourth step in the critical rending path is running layout on the render tree to compute the geometry of each node. <em>Layout</em> is the process by which the width, height, and location of all the nodes in the render tree are determined, plus the determination of the size and position of each object on the page. <em>Reflow</em> is any subsequent size and position determination of any part of the page or the entire document.</p>

<p>Once the render tree is built, layout commences. The render tree identified which nodes are displayed (even if invisible) along with their computed styles, but not the dimensions or location of each node. To determine the exact size and location of each object, the browser starts at the root of the render tree and traverses it.</p>

<p>On the web page, most everything is a box. Different devices and different desktop preferences mean an unlimited number of differing viewport sizes. In this phase, taking the viewport size into consideration, the browser determines what the dimensions of all the different boxes are going to be on the screen. Taking the size of the viewport as its base, layout generally starts with the body, laying out the dimensions of all the body’s descendants, with each element's box model properties, providing placeholder space for replaced elements it doesn’t know the dimensions of, such as our image.</p>

<p>The first time the size and position of nodes are determined is called <em>layout</em>. Subsequent recalculations of node size and locations are called <em>reflows</em>.  In our example, suppose the initial layout occurs before the image is returned. Since we didn't declare the size of our image, there will be a reflow once the image size is known.</p>

<h3 id="Paint">Paint</h3>

<p>The last step in the critical rendering path is painting the individual nodes to the screen, the first occurence of which is called the <a href="/en-US/docs/Glossary/first_meaningful_paint">first meaningful paint</a>. In the painting or rasterization phase, the browser converts each box calculated in the layout phase to actual pixels on the screen. Painting involves drawing every visual part of an element to the screen, including text, colors, borders, shadows, and replaced elements like buttons and images. The browser needs to do this super quickly.</p>

<p>To ensure smooth scrolling and animation, everything occupying the main thread, including calculating styles, along with reflow and paint, must take the browser less than 16.67ms to accomplish. At 2048 X 1536, the iPad has over 3,145,000 pixels to be painted to the screen. That is a lot of pixels that have to be painted very quickly. To ensure repainting can be done even faster than the initial paint, the drawing to the screen is generally broken down into several layers. If this occurs, then compositing is necessary.</p>

<p>Painting can break the elements in the layout tree into layers. Promoting content into layers on the GPU (instead of the main thread on the CPU) improves paint and repaint performance. There are specific properties and elements that instantiate a layer, including <code><a href="/en-US/docs/Web/HTML/Element/video">&lt;video&gt;</a></code> and <code><a href="/en-US/docs/Web/HTML/Element/canvas">&lt;canvas&gt;</a></code>, and any element which has the CSS properties of <a href="/en-US/docs/Web/CSS/opacity"><code>opacity</code></a>, a 3D <code><a href="/en-US/docs/Web/CSS/transform">transform</a></code>, <code><a href="/en-US/docs/Web/CSS/will-change">will-change</a></code>, and a few others. These nodes will be painted onto their own layer, along with their descendants, unless a descendant necessitates its own layer for one (or more) of the above reasons.</p>

<p>Layers do improve performance, but are expensive when it comes to memory management, so should not be overused as part of web performance optimization strategies.</p>

<h3 id="Compositing">Compositing</h3>

<p>When sections of the document are drawn in different layers, overlapping each other, compositing is necessary to ensure they are drawn to the screen in the right order and the content is rendered correctly.</p>

<p>As the page continues to load assets, reflows can happen (recall our example image that arrived late).  A reflow sparks a repaint and a re-composite. Had we defined the size of our image, no reflow would have been necessary, and only the layer that needed to be repainted would be repainted, and composited if necessary. But we didn't include the image size! When the image is obtained from the server, the rendering process goes back to the layout steps and restarts from there.</p>

<h2 id="Interactivity">Interactivity</h2>

<p>Once the main thread is done painting the page, you would think we would be "all set." That isn't necessarily the case. If the load includes JavaScript, that was correctly deferred, and only executed after the <code><a href="/en-US/docs/Web/API/GlobalEventHandlers/onload">onload</a></code> event fires, the main thread might be busy, and not available for scrolling, touch, and other interactions.</p>

<p>{{glossary('Time to Interactive')}} (TTI) is the measurement of how long it took from that first request which led to the DNS lookup and SSL connection to when the page is interactive -- interactive being the point in time after the {{glossary('First Contentful Paint')}} when the page responds to user interactions within 50ms. If the main thread is occupied parsing, compiling, and executing JavaScript, it is not available and therefore not able to responsd to user interactions in a timely (less than 50ms) fashion.</p>

<p>In our example, maybe the image loaded quickly, but perhaps the <code>anotherscript.js</code> file was 2MB and our user's network connection was slow.  In this case the user would see the page super quickly, but wouldn't be able to scroll without jank until the script was downloaded, parsed and executed. That is not a good user experience. Avoid occupying the main thread, as demonstrated in this WebPageTest example:</p>

<p><img alt="The main thread is occupied by the downloading, parsing and execution of a  javascript file - over a fast connection" src="https://mdn.mozillademos.org/files/16760/visa_network.png" style="height: 699px; width: 1200px;"></p>

<p>In this example, the DOM content load process took over 1.5 seconds, and the main thread was fully occupied that entire time, unresponsive to click events or screen taps.</p>

<h2 id="See_Also">See Also</h2>

<ul>
 <li><a href="/en-US/docs/Web/Performance">Web Performance</a></li>
</ul>