title: Async Fragments: Rediscovering Progressive HTML Rendering with Marko
url: http://www.ebaytechblog.com/2014/12/08/async-fragments-rediscovering-progressive-html-rendering-with-marko/
hash_url: 37bacf0c487ec399cba44cc8eb187e19

<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>
<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>
<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>
<h2>Background</h2>
<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>
<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>
<h2>Without progressive HTML rendering</h2>
<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>
<p><img src="https://docs.google.com/uc?authuser=0&amp;id=0B68ucl6PKE9yV0pfOUZHRXVuTlU&amp;export=download" alt="Single Flush Waterfall Chart"/></p>
<p>The corresponding page controller might look something like this:</p>
<pre>function controller(req, res) {&#13;
    async.parallel([&#13;
            function loadSearchResults(callback) {&#13;
                ...&#13;
            },&#13;
            function loadFilters(callback) {&#13;
                ...&#13;
            },&#13;
            function loadAds(callback) {&#13;
                ...&#13;
            }&#13;
        ],&#13;
        function() {&#13;
            ...&#13;
            var viewModel = { ... };&#13;
            res.render('search', viewModel);&#13;
        })&#13;
}</pre>
<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>
<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>
<h2>Flushing the head early</h2>
<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>
<p><img src="https://docs.google.com/uc?authuser=0&amp;id=0B68ucl6PKE9yTWttODlfWVR5N3M&amp;export=download" alt="Flush Head Waterfall Chart"/></p>
<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>
<h2>Multiple flushes</h2>
<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>
<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>
<h3>In-order flushing of async fragments</h3>
<p>As an example, let’s assume we have divided a complex page into the following fragments:</p>
<p><img src="https://docs.google.com/uc?authuser=0&amp;id=0B68ucl6PKE9yUnI2UU9LQWluS28&amp;export=download" alt="Page diagram"/></p>
<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>
<pre>&lt;html&gt;&#13;
&lt;head&gt;&#13;
    &lt;title&gt;Clothing Store&lt;/title&gt;&#13;
    &lt;!-- 1a) Head &lt;link&gt; tags --&gt;&#13;
&lt;/head&gt;&#13;
&lt;body&gt;&#13;
    &lt;header&gt;&#13;
       &lt;!-- 1b) Header --&gt;&#13;
    &lt;/header&gt;&#13;
    &lt;div class="body"&gt;&#13;
        &lt;main&gt;&#13;
            &lt;!-- 2) Search Results --&gt;&#13;
        &lt;/main&gt;&#13;
        &lt;section class="filters"&gt;&#13;
            &lt;!-- 3) Search filters --&gt;&#13;
        &lt;/section&gt;&#13;
        &lt;section class="ads"&gt;&#13;
            &lt;!-- 4) Ads --&gt;&#13;
        &lt;/section&gt;&#13;
    &lt;/div&gt;&#13;
    &lt;footer&gt;&#13;
        &lt;!-- 5a) Footer --&gt;&#13;
    &lt;/footer&gt;&#13;
    &lt;!-- 5b) Body &lt;script&gt; tags --&gt;&#13;
&lt;/body&gt;&#13;
&lt;/html&gt;</pre>
<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>
<p>Continuing with the previous example, our HTML page template with asynchronous fragments defined will be similar to the following:</p>
<pre>&lt;html&gt;&#13;
&lt;head&gt;&#13;
    &lt;title&gt;Clothing Store&lt;/title&gt;&#13;
    &lt;!-- Head &lt;link&gt; tags --&gt;&#13;
&lt;/head&gt;&#13;
&lt;body&gt;&#13;
    &lt;header&gt;&#13;
        &lt;!-- Header --&gt;&#13;
    &lt;/header&gt;&#13;
    &lt;div class="body"&gt;&#13;
        &lt;main&gt;&#13;
            &lt;!-- Search Results --&gt;&#13;
            &lt;async-fragment data-provider="data.searchResultsProvider"&#13;
                var="searchResults"&gt;&#13;
&#13;
                &lt;!-- Do something with the search results data... --&gt;&#13;
                &lt;ul&gt;&#13;
                    &lt;li for="item in searchResults.items"&gt;&#13;
                        $item.title&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
            &lt;/async-fragment&gt;&#13;
        &lt;/main&gt;&#13;
        &lt;section class="filters"&gt;&#13;
&#13;
            &lt;!-- Search filters --&gt;&#13;
            &lt;async-fragment data-provider="data.filtersProvider"&#13;
                var="filters"&gt;&#13;
                &lt;!-- Do something with the filters data... --&gt;&#13;
            &lt;/async-fragment&gt;&#13;
&#13;
        &lt;/section&gt;&#13;
        &lt;section class="ads"&gt;&#13;
&#13;
            &lt;!-- Ads --&gt;&#13;
            &lt;async-fragment data-provider="data.adsProvider"&#13;
                var="ads"&gt;&#13;
                &lt;!-- Do something with the ads data... --&gt;&#13;
            &lt;/async-fragment&gt;&#13;
&#13;
        &lt;/section&gt;&#13;
    &lt;/div&gt;&#13;
    &lt;footer&gt;&#13;
        &lt;!-- Footer --&gt;&#13;
    &lt;/footer&gt;&#13;
    &lt;!-- Body &lt;script&gt; tags --&gt;&#13;
&lt;/body&gt;&#13;
&lt;/html&gt;&#13;
</pre>
<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>
<pre>function controller(req, res) {&#13;
    template.render({&#13;
            searchResultsProvider: function(callback) {&#13;
                performSearch(req.params.category, callback);&#13;
            },&#13;
&#13;
            filtersProvider: function(callback) {&#13;
                ...&#13;
            },&#13;
&#13;
            adsProvider: function(callback) {&#13;
                ...&#13;
            }&#13;
        },&#13;
        res /* Render directly to the output HTTP response stream */);&#13;
}</pre>
<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>
<p><img src="https://docs.google.com/uc?authuser=0&amp;id=0B68ucl6PKE9yZ0RTLWtINVlobHc&amp;export=download" alt="In-order Flush Waterfall Chart"/></p>
<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>
<h3>Out-of-order flushing of async fragments</h3>
<p>Marko achieves out-of-order flushing of async fragments by doing the following:</p>
<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>
<p>To clarify, here is what the output HTML might look like for a page with out-of-order flushing enabled:</p>
<pre>&lt;html&gt;&#13;
&lt;head&gt;&#13;
    &lt;title&gt;Clothing Store&lt;/title&gt;&#13;
    &lt;!-- 1a) Head &lt;link&gt; tags --&gt;&#13;
&lt;/head&gt;&#13;
&lt;body&gt;&#13;
    &lt;header&gt;&#13;
        &lt;!-- 1b) Header --&gt;&#13;
    &lt;/header&gt;&#13;
    &lt;div class="body"&gt;&#13;
        &lt;main&gt;&#13;
            &lt;!-- 2) Search Results --&gt;&#13;
            &lt;span id="asyncFragment0Placeholder"&gt;&lt;/span&gt;&#13;
        &lt;/main&gt;&#13;
        &lt;section class="filters"&gt;&#13;
            &lt;!-- 3) Search filters --&gt;&#13;
            &lt;span id="asyncFragment1Placeholder"&gt;&lt;/span&gt;&#13;
        &lt;/section&gt;&#13;
        &lt;section class="ads"&gt;&#13;
            &lt;!-- 4) Ads --&gt;&#13;
            &lt;span id="asyncFragment2Placeholder"&gt;&lt;/span&gt;&#13;
        &lt;/section&gt;&#13;
    &lt;/div&gt;&#13;
    &lt;footer&gt;&#13;
        &lt;!-- 5a) Footer --&gt;&#13;
    &lt;/footer&gt;&#13;
&#13;
    &lt;!-- 5b) Body &lt;script&gt; tags --&gt;&#13;
&#13;
    &lt;script&gt;&#13;
    window.$af=function(){&#13;
    // Small amount of code to support rearranging DOM nodes&#13;
    // Unminified:&#13;
    // https://github.com/raptorjs/marko-async/blob/master/client-reorder-runtime.js&#13;
    };&#13;
    &lt;/script&gt;&#13;
&#13;
    &lt;div id="asyncFragment1" style="display:none"&gt;&#13;
        &lt;!-- 4) Ads content --&gt;&#13;
    &lt;/div&gt;&#13;
    &lt;script&gt;$af(1)&lt;/script&gt;&#13;
&#13;
    &lt;div id="asyncFragment2" style="display:none"&gt;&#13;
        &lt;!-- 3) Search filters content --&gt;&#13;
    &lt;/div&gt;&#13;
    &lt;script&gt;$af(2)&lt;/script&gt;&#13;
&#13;
    &lt;div id="asyncFragment0" style="display:none"&gt;&#13;
        &lt;!-- 2) Search results content --&gt;&#13;
    &lt;/div&gt;&#13;
    &lt;script&gt;$af(0)&lt;/script&gt;&#13;
&#13;
&lt;/body&gt;&#13;
&lt;/html&gt;&#13;
</pre>
<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>
<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>
<pre>&lt;async-fragment data-provider="data.searchResultsProvider"&#13;
    var="searchResults"&#13;
    client-reorder="true&gt;&#13;
    ...&#13;
&lt;/async-fragment&gt;</pre>
<p>The updated HTML page template with the new <code>&lt;async-fragments&gt;</code> tag is shown below:</p>
<pre>&lt;html&gt;&#13;
&lt;head&gt;&#13;
    &lt;title&gt;Clothing Store&lt;/title&gt;&#13;
    &lt;!-- Head &lt;link&gt; tags &gt;&#13;
&lt;/head&gt;&#13;
&lt;body&gt;&#13;
    ...&#13;
&#13;
    &lt;!-- Body &lt;script&gt; tags --&gt;&#13;
&#13;
    &lt;async-fragments/&gt;&#13;
&lt;/body&gt;&#13;
&lt;/html&gt;</pre>
<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>
<p>Our final waterfall with out-of-order flushing will now be similar to the following:</p>
<p><img src="https://docs.google.com/uc?authuser=0&amp;id=0B68ucl6PKE9yanJFNTN3SWxwX2s&amp;export=download" alt="Out-of-order Flush Waterfall Chart"/></p>
<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>
<h2>Additional considerations</h2>
<h3>HTTP Transport and HTML compression</h3>
<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>
<h3>Binding behavior</h3>
<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>
<h3>Error handling</h3>
<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>
<h2>Summary</h2>
<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>
<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>
<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>
