A place to cache linked articles (think custom and personal wayback machine)
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

4 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. title: Async Fragments: Rediscovering Progressive HTML Rendering with Marko
  2. url: http://www.ebaytechblog.com/2014/12/08/async-fragments-rediscovering-progressive-html-rendering-with-marko/
  3. hash_url: 37bacf0c487ec399cba44cc8eb187e19
  4. <p>At eBay, we take site speed very seriously and are always looking for ways to allow developers to create faster-loading web apps. This involves fully understanding and controlling how web pages are delivered to web browsers. Progressive HTML rendering is a relatively old technique that can be used to improve the performance of websites, but it has been lost in a whole new class of web applications. The idea is simple: give the web browser a head start in downloading and rendering the page by flushing out early and multiple times. Browsers have always had the helpful feature of parsing and responding to the HTML as it is being streamed down from the server (even before the response is ended). This feature allows the HTML and external resources to be downloaded earlier, and for parts of the page to be rendered earlier. As a result, both the actual load time and the perceived load time improve.</p>
  5. <p>In this blog post, we will take an in-depth look at a technique we call “Async Fragments” that takes advantage of progressive HTML rendering to improve site speed in ways that do not drastically complicate how web applications are built. For concrete examples we will be using <a href="http://nodejs.org/">Node.js</a>, <a href="http://expressjs.com/">Express.js</a> and the <a href="https://github.com/raptorjs/marko">Marko templating engine</a> (a JavaScript templating engine that supports streaming, flushing, and asynchronous rendering). Even if you are not using these technologies, this post can give you insight into how your stack of choice could be further optimized.</p>
  6. <p>To see the techniques discussed in this post in action, please take a look at the <a href="https://marko-progressive-rendering.herokuapp.com/">accompanying sample application</a>.</p>
  7. <h2>Background</h2>
  8. <p>Progressive HTML rendering is discussed in the post <a href="http://blog.codinghorror.com/the-lost-art-of-progressive-html-rendering/">The Lost Art of Progressive HTML Rendering</a> by Jeff Atwood, which was published back in 2005. In addition, the “Flush the Buffer Early” rule is described by the Yahoo! Performance team in their <a href="https://developer.yahoo.com/performance/rules.html#flush">Best Practices for Speeding Up Your Web Site</a> guide. Stoyan Stefanov provides an in-depth look at progressive HTML rendering in his <a href="http://www.phpied.com/progressive-rendering-via-multiple-flushes/">Progressive rendering via multiple flushes</a> post. Facebook discussed how they use a technique they call <a href="https://www.facebook.com/notes/facebook-engineering/bigpipe-pipelining-web-pages-for-high-performance/389414033919">“BigPipe”</a> to improve page load times and perceived performance by dividing up a page into “pagelets.” Those articles and techniques inspired many of the ideas discussed in this post.</p>
  9. <p>In the Node.js world, its most popular web framework, <a href="http://expressjs.com/">Express.js</a>, unfortunately recommends a view rendering engine that does not allow streaming and thus prevents progressive HTML rendering. In a recent post, <a href="http://strongloop.com/strongblog/bypassing-express-view-rendering-for-speed-and-modularity/">Bypassing Express View Rendering for Speed and Modularity</a>, I described how streaming can be achieved with Express.js; this post is largely a follow-up to discuss how progressive HTML rendering can be achieved with Node.js (with or without Express.js).</p>
  10. <h2>Without progressive HTML rendering</h2>
  11. <p>A page that does not utilize progressive HTML rendering will have a slower load time because the bytes will not be flushed out until the complete HTML response is built. In addition, after the client finally receives the <em>complete</em> HTML it will then see that it needs to download additional external resources (such as CSS, JavaScript, fonts, and images), and downloading these external resources will require additional round trips. In addition, pages that do not utilize progressive HTML rendering will also have a slower perceived load time, since the screen will not update until the complete HTML is downloaded <em>and</em> the CSS and fonts referenced in the <code>&lt;head&gt;</code> section are downloaded. Without progressive HTML rendering, a server/client waterfall chart might be similar to the following:</p>
  12. <p><img src="https://docs.google.com/uc?authuser=0&amp;id=0B68ucl6PKE9yV0pfOUZHRXVuTlU&amp;export=download" alt="Single Flush Waterfall Chart"/></p>
  13. <p>The corresponding page controller might look something like this:</p>
  14. <pre>function controller(req, res) {&#13;
  15. async.parallel([&#13;
  16. function loadSearchResults(callback) {&#13;
  17. ...&#13;
  18. },&#13;
  19. function loadFilters(callback) {&#13;
  20. ...&#13;
  21. },&#13;
  22. function loadAds(callback) {&#13;
  23. ...&#13;
  24. }&#13;
  25. ],&#13;
  26. function() {&#13;
  27. ...&#13;
  28. var viewModel = { ... };&#13;
  29. res.render('search', viewModel);&#13;
  30. })&#13;
  31. }</pre>
  32. <p>As you can see in the above code, the page HTML is not rendered until <em>all</em> of the data is asynchronously loaded.</p>
  33. <p>Because the HTML is not flushed until all back-end services are completed, the user will be staring at a blank screen for a large portion of the time. This will result in a sub-par user experience (especially with a poor network connection or with slow back-end services). We can do much better if we flush part of the HTML earlier.</p>
  34. <h2>Flushing the head early</h2>
  35. <p>A simple trick to improve the responsiveness of a website is to flush the head section immediately. The head section will typically include the links to the external CSS resources (i.e. the <code>&lt;link&gt;</code> tags), as well as the page header and navigation. With this approach the external CSS will be downloaded sooner and the initial page will be painted much sooner as shown in the following waterfall chart:</p>
  36. <p><img src="https://docs.google.com/uc?authuser=0&amp;id=0B68ucl6PKE9yTWttODlfWVR5N3M&amp;export=download" alt="Flush Head Waterfall Chart"/></p>
  37. <p>As you can see in the chart above, flushing the head early reduces the time to render the initial page. This technique improves the responsiveness of the page, but it does not significantly reduce the total time it takes to make the page fully functional. With this approach, the server is still waiting for all back-end services to complete before flushing the final HTML. In addition, downloading of external JavaScript resources will be delayed since <code>&lt;script&gt;</code> tags are placed at the end of the page (assuming you are following best practices) and don’t get sent out until the second and final flush.</p>
  38. <h2>Multiple flushes</h2>
  39. <p>Instead of flushing only the head early, it is often beneficial to flush multiple times before ending the response. Typically, a page can be divided into multiple fragments where some of the fragments may depend on data asynchronously loaded from various back-end services while others may not depend on any asynchronously loaded data. The fragments that depend on asynchronously loaded data should be rendered asynchronously and flushed as soon as possible.</p>
  40. <p>For now, we will assume that these fragments need to be flushed in the proper HTML order (versus the order that the data asynchronously loads), but we will also show how out-of-order flushing can be used to further improve both page load times and perceived performance. When using “in-order” flushing, fragments that complete out of order will need to be buffered until they are ready to be flushed in the proper order.</p>
  41. <h3>In-order flushing of async fragments</h3>
  42. <p>As an example, let’s assume we have divided a complex page into the following fragments:</p>
  43. <p><img src="https://docs.google.com/uc?authuser=0&amp;id=0B68ucl6PKE9yUnI2UU9LQWluS28&amp;export=download" alt="Page diagram"/></p>
  44. <p>Each fragment is assigned a number based on the order that it appears in the HTML document. In code, our output HTML for the page might look like the following:</p>
  45. <pre>&lt;html&gt;&#13;
  46. &lt;head&gt;&#13;
  47. &lt;title&gt;Clothing Store&lt;/title&gt;&#13;
  48. &lt;!-- 1a) Head &lt;link&gt; tags --&gt;&#13;
  49. &lt;/head&gt;&#13;
  50. &lt;body&gt;&#13;
  51. &lt;header&gt;&#13;
  52. &lt;!-- 1b) Header --&gt;&#13;
  53. &lt;/header&gt;&#13;
  54. &lt;div class="body"&gt;&#13;
  55. &lt;main&gt;&#13;
  56. &lt;!-- 2) Search Results --&gt;&#13;
  57. &lt;/main&gt;&#13;
  58. &lt;section class="filters"&gt;&#13;
  59. &lt;!-- 3) Search filters --&gt;&#13;
  60. &lt;/section&gt;&#13;
  61. &lt;section class="ads"&gt;&#13;
  62. &lt;!-- 4) Ads --&gt;&#13;
  63. &lt;/section&gt;&#13;
  64. &lt;/div&gt;&#13;
  65. &lt;footer&gt;&#13;
  66. &lt;!-- 5a) Footer --&gt;&#13;
  67. &lt;/footer&gt;&#13;
  68. &lt;!-- 5b) Body &lt;script&gt; tags --&gt;&#13;
  69. &lt;/body&gt;&#13;
  70. &lt;/html&gt;</pre>
  71. <p>The Marko templating engine provides a way to declaratively bind template fragments to asynchronous data provider functions (or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a>). An asynchronous fragment is rendered when the asynchronous data provider function invokes the provided callback with the data. If the asynchronous fragment is ready to be flushed, then it is immediately flushed to the output stream. Otherwise, if the asynchronous fragment completed out of order then the rendered HTML is buffered in memory until it is ready to be flushed. The Marko templating engine ensures that fragments are flushed in the proper order.</p>
  72. <p>Continuing with the previous example, our HTML page template with asynchronous fragments defined will be similar to the following:</p>
  73. <pre>&lt;html&gt;&#13;
  74. &lt;head&gt;&#13;
  75. &lt;title&gt;Clothing Store&lt;/title&gt;&#13;
  76. &lt;!-- Head &lt;link&gt; tags --&gt;&#13;
  77. &lt;/head&gt;&#13;
  78. &lt;body&gt;&#13;
  79. &lt;header&gt;&#13;
  80. &lt;!-- Header --&gt;&#13;
  81. &lt;/header&gt;&#13;
  82. &lt;div class="body"&gt;&#13;
  83. &lt;main&gt;&#13;
  84. &lt;!-- Search Results --&gt;&#13;
  85. &lt;async-fragment data-provider="data.searchResultsProvider"&#13;
  86. var="searchResults"&gt;&#13;
  87. &#13;
  88. &lt;!-- Do something with the search results data... --&gt;&#13;
  89. &lt;ul&gt;&#13;
  90. &lt;li for="item in searchResults.items"&gt;&#13;
  91. $item.title&#13;
  92. &lt;/li&gt;&#13;
  93. &lt;/ul&gt;&#13;
  94. &#13;
  95. &lt;/async-fragment&gt;&#13;
  96. &lt;/main&gt;&#13;
  97. &lt;section class="filters"&gt;&#13;
  98. &#13;
  99. &lt;!-- Search filters --&gt;&#13;
  100. &lt;async-fragment data-provider="data.filtersProvider"&#13;
  101. var="filters"&gt;&#13;
  102. &lt;!-- Do something with the filters data... --&gt;&#13;
  103. &lt;/async-fragment&gt;&#13;
  104. &#13;
  105. &lt;/section&gt;&#13;
  106. &lt;section class="ads"&gt;&#13;
  107. &#13;
  108. &lt;!-- Ads --&gt;&#13;
  109. &lt;async-fragment data-provider="data.adsProvider"&#13;
  110. var="ads"&gt;&#13;
  111. &lt;!-- Do something with the ads data... --&gt;&#13;
  112. &lt;/async-fragment&gt;&#13;
  113. &#13;
  114. &lt;/section&gt;&#13;
  115. &lt;/div&gt;&#13;
  116. &lt;footer&gt;&#13;
  117. &lt;!-- Footer --&gt;&#13;
  118. &lt;/footer&gt;&#13;
  119. &lt;!-- Body &lt;script&gt; tags --&gt;&#13;
  120. &lt;/body&gt;&#13;
  121. &lt;/html&gt;&#13;
  122. </pre>
  123. <p>The data provider functions should be passed to the template as part of the view model as shown in the following code for a sample page controller:</p>
  124. <pre>function controller(req, res) {&#13;
  125. template.render({&#13;
  126. searchResultsProvider: function(callback) {&#13;
  127. performSearch(req.params.category, callback);&#13;
  128. },&#13;
  129. &#13;
  130. filtersProvider: function(callback) {&#13;
  131. ...&#13;
  132. },&#13;
  133. &#13;
  134. adsProvider: function(callback) {&#13;
  135. ...&#13;
  136. }&#13;
  137. },&#13;
  138. res /* Render directly to the output HTTP response stream */);&#13;
  139. }</pre>
  140. <p>In this particular example, the “search results” async fragment appears first in the HTML template, and it happens to take the longest time to complete. As a result, all of the subsequent fragments will need to be buffered on the server. The resulting waterfall with in-order flushing of async fragments is shown below:</p>
  141. <p><img src="https://docs.google.com/uc?authuser=0&amp;id=0B68ucl6PKE9yZ0RTLWtINVlobHc&amp;export=download" alt="In-order Flush Waterfall Chart"/></p>
  142. <p>While the performance of this approach might be fine, we can enable out-of-order flushing for further performance gains as described in the next section.</p>
  143. <h3>Out-of-order flushing of async fragments</h3>
  144. <p>Marko achieves out-of-order flushing of async fragments by doing the following:</p>
  145. <p>Instead of waiting for an async fragment to finish, a placeholder HTML element with an assigned <code>id</code> is written to the output stream. Out-of-order async fragments are rendered before the ending <code>&lt;body&gt;</code> tag in the order that they complete. Each out-of-order async fragment is rendered into a hidden <code>&lt;div&gt;</code> element. Immediately after the out-of-order fragment, a <code>&lt;script&gt;</code> block is rendered to replace the placeholder DOM node with the DOM nodes of the corresponding out-of-order fragment. When all of the out-of-order async fragments complete, the remaining HTML (e.g. <code>&lt;/body&gt;&lt;/html&gt;</code>) will be flushed and the response ended.</p>
  146. <p>To clarify, here is what the output HTML might look like for a page with out-of-order flushing enabled:</p>
  147. <pre>&lt;html&gt;&#13;
  148. &lt;head&gt;&#13;
  149. &lt;title&gt;Clothing Store&lt;/title&gt;&#13;
  150. &lt;!-- 1a) Head &lt;link&gt; tags --&gt;&#13;
  151. &lt;/head&gt;&#13;
  152. &lt;body&gt;&#13;
  153. &lt;header&gt;&#13;
  154. &lt;!-- 1b) Header --&gt;&#13;
  155. &lt;/header&gt;&#13;
  156. &lt;div class="body"&gt;&#13;
  157. &lt;main&gt;&#13;
  158. &lt;!-- 2) Search Results --&gt;&#13;
  159. &lt;span id="asyncFragment0Placeholder"&gt;&lt;/span&gt;&#13;
  160. &lt;/main&gt;&#13;
  161. &lt;section class="filters"&gt;&#13;
  162. &lt;!-- 3) Search filters --&gt;&#13;
  163. &lt;span id="asyncFragment1Placeholder"&gt;&lt;/span&gt;&#13;
  164. &lt;/section&gt;&#13;
  165. &lt;section class="ads"&gt;&#13;
  166. &lt;!-- 4) Ads --&gt;&#13;
  167. &lt;span id="asyncFragment2Placeholder"&gt;&lt;/span&gt;&#13;
  168. &lt;/section&gt;&#13;
  169. &lt;/div&gt;&#13;
  170. &lt;footer&gt;&#13;
  171. &lt;!-- 5a) Footer --&gt;&#13;
  172. &lt;/footer&gt;&#13;
  173. &#13;
  174. &lt;!-- 5b) Body &lt;script&gt; tags --&gt;&#13;
  175. &#13;
  176. &lt;script&gt;&#13;
  177. window.$af=function(){&#13;
  178. // Small amount of code to support rearranging DOM nodes&#13;
  179. // Unminified:&#13;
  180. // https://github.com/raptorjs/marko-async/blob/master/client-reorder-runtime.js&#13;
  181. };&#13;
  182. &lt;/script&gt;&#13;
  183. &#13;
  184. &lt;div id="asyncFragment1" style="display:none"&gt;&#13;
  185. &lt;!-- 4) Ads content --&gt;&#13;
  186. &lt;/div&gt;&#13;
  187. &lt;script&gt;$af(1)&lt;/script&gt;&#13;
  188. &#13;
  189. &lt;div id="asyncFragment2" style="display:none"&gt;&#13;
  190. &lt;!-- 3) Search filters content --&gt;&#13;
  191. &lt;/div&gt;&#13;
  192. &lt;script&gt;$af(2)&lt;/script&gt;&#13;
  193. &#13;
  194. &lt;div id="asyncFragment0" style="display:none"&gt;&#13;
  195. &lt;!-- 2) Search results content --&gt;&#13;
  196. &lt;/div&gt;&#13;
  197. &lt;script&gt;$af(0)&lt;/script&gt;&#13;
  198. &#13;
  199. &lt;/body&gt;&#13;
  200. &lt;/html&gt;&#13;
  201. </pre>
  202. <p>One caveat with out-of-order flushing is that it requires JavaScript running on the client to move each out-of-order fragment into its proper place in the DOM. Thus, you would only want to enable out-of-order flushing if you know that the client’s web browser has JavaScript enabled. Also, moving DOM nodes may cause the page to be reflowed, which can be visually jarring to the user and result in more client-side CPU usage. If reflow is an issue then there are tricks that can be used to avoid a reflow (e.g., reserving space as part of the initial wireframe). Marko also allows alternative content to be shown while waiting for an out-of-order async fragment.</p>
  203. <p>To enable out-of-order flushing with Marko, the <code>client-reorder="true"</code> attribute must be added to each <code>&lt;async-fragment&gt;</code> tag, and the <code>&lt;async-fragments&gt;</code> tag must be added to the end of the page to serve as the container for rendered out-of-order fragments. Here is the updated <code>&lt;async-fragment&gt;</code> tag for the search results fragment:</p>
  204. <pre>&lt;async-fragment data-provider="data.searchResultsProvider"&#13;
  205. var="searchResults"&#13;
  206. client-reorder="true&gt;&#13;
  207. ...&#13;
  208. &lt;/async-fragment&gt;</pre>
  209. <p>The updated HTML page template with the new <code>&lt;async-fragments&gt;</code> tag is shown below:</p>
  210. <pre>&lt;html&gt;&#13;
  211. &lt;head&gt;&#13;
  212. &lt;title&gt;Clothing Store&lt;/title&gt;&#13;
  213. &lt;!-- Head &lt;link&gt; tags &gt;&#13;
  214. &lt;/head&gt;&#13;
  215. &lt;body&gt;&#13;
  216. ...&#13;
  217. &#13;
  218. &lt;!-- Body &lt;script&gt; tags --&gt;&#13;
  219. &#13;
  220. &lt;async-fragments/&gt;&#13;
  221. &lt;/body&gt;&#13;
  222. &lt;/html&gt;</pre>
  223. <p>In combination with out-of-order flushing, it may be beneficial to move <code>&lt;script&gt;</code> tags that link to external resources to the end of the first chunk (before all of the out-of-order chunks). While the server is busy preparing the rest of the page, the client can start downloading the external JavaScript required to make the page functional. As a result, the user will be able to start interacting with the page sooner.</p>
  224. <p>Our final waterfall with out-of-order flushing will now be similar to the following:</p>
  225. <p><img src="https://docs.google.com/uc?authuser=0&amp;id=0B68ucl6PKE9yanJFNTN3SWxwX2s&amp;export=download" alt="Out-of-order Flush Waterfall Chart"/></p>
  226. <p>The final waterfall shows that the strategy of out-of-order flushing of asynchronous fragments can significantly improve the load time <em>and</em> perceived load time of a page. The user will be met with a progressive loading of a page that is ready to be interacted with sooner.</p>
  227. <h2>Additional considerations</h2>
  228. <h3>HTTP Transport and HTML compression</h3>
  229. <p>To allow HTML to be served in parts, <a href="http://en.wikipedia.org/wiki/Chunked_transfer_encoding">chunked transfer encoding</a> should be used for the HTTP response. Chunked transfer encoding uses delimiters to break up the response, and each flush results in a new chunk. If gzip compression is enabled (and it should be) then flushing the pending data to the gzip stream will result in a gzip data frame being written to the response as part of each chunk. Flushing too often will negatively impact the effectiveness of the compression algorithm, but without flushing periodically then progressive HTML rendering will not be available. By default, Marko will flush at the beginning of an <code>&lt;async-fragment&gt;</code> block (in order to send everything that has already completed), as well as when an async fragment completes. This default strategy results in efficient progressive loading of an HTML page as long as there are not too many async fragments.</p>
  230. <h3>Binding behavior</h3>
  231. <p>For improved usability and responsiveness, there should not be a long delay between rendered HTML being displayed to the user in the web browser and behavior being attached to the associated DOM. At eBay, we use the <a href="https://github.com/raptorjs/marko-widgets">marko-widgets</a> module to bind behavior to DOM nodes. Marko Widgets supports binding behavior to rendered widgets immediately after each independent async fragment, as illustrated in the <a href="https://marko-progressive-rendering.herokuapp.com/">accompanying sample app</a>. For immediate binding to work, the required JavaScript code must be included <em>earlier</em> in the page. For more details, please see the marko-widgets module documentation.</p>
  232. <h3>Error handling</h3>
  233. <p>It is important to note that as soon as a byte is flushed for the HTTP body, then the response is committed; no additional HTTP headers can be sent (e.g., no server-side redirects or cookie-setting), and the HTML that has been sent cannot be “unsent”. Therefore, if an asynchronous data provider errors or times out, then the app must be prepared to show alternative content for <em>that</em> particular async fragment. Please see the documentation for the <a href="https://github.com/raptorjs/marko-async">marko-async</a> module for additional information on how to show alternative content in case of an error.</p>
  234. <h2>Summary</h2>
  235. <p>The Async Fragments technique allows web developers to maximize the benefits of progressive HTML rendering to produce web pages that have improved actual and perceived load times. Developers at eBay have found the concept of binding HTML template fragments to asynchronous data providers easy to grasp and utilize. In addition, the flexibility to support both in-order and out-of-order flushing of async fragments makes this technique applicable for all web browsers and user agents.</p>
  236. <p>The <a href="https://github.com/raptorjs/marko">Marko</a> templating engine is being used as part of eBay’s latest Node.js stack to improve performance while also simplifying how pages are constructed on both the server and the client. Marko is one of a few templating engines for Node.js and web browsers that support streaming, flushing, and asynchronous rendering. Marko has a simple HTML-based syntax, and the Marko compiler produces small and efficient JavaScript modules as output. We encourage you to <a href="http://raptorjs.org/marko/try-online/">try Marko online</a> and in your next Node.js project. Because Marko is a key component of eBay’s internal Node.js stack, and given that it is heavily documented and tested, you can be confident that it will be well supported.</p>
  237. <p><em>Patrick Steele-Idem is a member of eBay’s platform team who enjoys writing open-source software and improving how web applications are built. He is the author of <a href="http://raptorjs.org/">RaptorJS</a>, a suite of open-source front-end power tools that are being used within and outside eBay. You can follow Patrick on Twitter at <a href="https://twitter.com/psteeleidem">@psteeleidem</a>.</em></p>