Example: Building a UI with AsyncQueue

This example illustrates how to break up the initial rendering of an application UI into queued code chunks, yielding back to the browser regularly to draw portions of the UI as they become ready.

Note: This method should be reserved for apps constructing complex DOM structures. While the DOM structure contained in this example is not complex, some artificial delays are injected to simulate process-intensive operations that would normally cause such delays.

The module will be inserted here. Click the button below.

The Markup

The markup will start with just a placeholder element for our application.

<div id="demo">
    <p>The module will be inserted here.  <em>Click the button below</em>.</p>
</div>

<button id="init">Initialize Application</button>

The markup will eventually evolve to the following as the script runs (indented for readability):

<div id="demo">
    <div class="yui3-module">
        <div class="yui3-hd">
            <h4>AsyncQueue Demo</h4>
        </div>
        <div class="yui3-bd">
            <div class="yui3-nav">
                <ul class="yui3-g">
                    <li class="yui3-u-1-4"><a href="#">Nav Lorem</a></li>
                    <li class="yui3-u-1-4"><a href="#">Nav Ipsum</a></li>
                    <li class="yui3-u-1-4"><a href="#">Nav Dolor</a></li>
                    <li class="yui3-u-1-4"><a href="#">Nav Sit</a></li>
                </ul>
            </div>
            <div class="yui3-content">
                <p>[ App content here ]</p>
            </div>
        </div>
        <div class="yui3-ft">
            <p class="yui3-status">(status message here)</p>
        </div>
    </div>
</div>

<button id="init">Re-initialize Application</button>

The CSS

Some CSS is added to make it look like an application.

<style>
    #init {
        margin-top: 1em;
    }

    #demo .yui3-module {
        position: relative;
        width: 28em;
    }
    #demo .yui3-module .yui3-hd,
    #demo .yui3-module .yui3-bd,
    #demo .yui3-module .yui3-ft {
        margin: 0;
        padding: 1ex 1em;
    }
    #demo .yui3-module .yui3-hd {
        background: #406ED9;
    }
    #demo .yui3-module .yui3-hd h4 {
        color: #fff;
        margin: 0;
    }
    #demo .yui3-module .yui3-bd {
        background: #ABCEFF;
        border-left: 1px solid #7A97BB;
        border-right: 1px solid #7A97BB;
        height: 5em;
        padding-top: 4.5em;
        position: relative;
        overflow: hidden;
        text-align: center;
    }
    #demo .yui3-module .yui3-ft {
        background: #fff;
        border: 1px solid #7A97BB;
        border-top-color: #ccc;
        padding-right: 25px;
    }
    #demo .yui3-module .yui3-status {
        margin: 0;
        padding: 0 25px 0 0;
        height: 1.3em;
    }
    #demo .yui3-module .yui3-nav {
        background: #fff;
        border-bottom: 1px solid #ccc;
        left: 0;
        padding: .5em;
        position: absolute;
        width: 27em;
    }
    #demo .yui3-module .yui3-nav ul,
    #demo .yui3-module .yui3-nav li {
        list-style: none;
        margin: 0;
        padding: 0;
    }
    #demo .yui3-module .yui3-nav a {
        color: #ffa928;
    }
    #demo .yui3-module .working {
        background: #fff url(http://l.yimg.com/a/i/nt/ic/ut/bsc/busyarr_1.gif) no-repeat 26em 50%;
    }
</style>

Example application structure

For this example, we'll create a simple application that we'll contain under the MyApp namespace. The basic structure of the namespace will be as follows:

YUI().use("node", "transition", "async-queue", function (Y) {

var MyApp = {
    // the name of the application
    NAME : "AsyncQueue Demo",

    // rendering AsyncQueue
    q : new Y.AsyncQueue(),

    // cache of frequently used nodes in the DOM structure
    nodes : {
        root    : null,
        status  : null,
        nav     : null,
        content : null,
        foot    : null
    },

    /*** Public API methods ***/
    // draws the UI in the specified container
    render : function (container) { ... },

    // update the status bar at the bottom of the app
    setStatus : function (message,working) { ... },


    /*** private methods ***/
    // adds the basic app skeleton to the page
    _renderFramework : function () { ... },

    // populates the navigation section
    _renderNav : function () { ... },

    // populates the content section
    _renderContent : function () { ... }
};

});

The MyApp.render function will add the rendering methods to the MyApp.q AsyncQueue and set it in motion. Each of the methods will be executed in turn, yielding back to the browser between steps. So as each piece of the UI is assembled, the browser is given the opportunity to draw it.

...
render : function (container) {
    // If the application is currently rendered somewhere, destroy it first
    // by clearing the queue and adding the destroy method to run before
    // the default rendering operations.
    if (MyApp.nodes.root) {
        MyApp.q.stop();

        MyApp.q.add(
            MyApp.destroy
        );
    }

    // Add the rendering operations to the ops.render queue and call run()
    MyApp.q.add(
        // pass the container param to the callback using Y.bind
        Y.bind(MyApp._renderFramework, MyApp, container),
        MyApp._renderNav,
        MyApp._renderContent).run();
},
...

If there are any process-intensive operations in the rendering steps, the UI generated in all previous steps will have been drawn by the browser before the heavy lifting begins. This way, the user will be shown a part of the UI and can begin to develop an understanding of its structure and operation while the rest of it is being constructed.

A note on artificial delays and animation

In this example, rather than include code that would spike your CPU, delays were simulated by inserting AsyncQueue callbacks with a timeout and a function that does nothing. There is a distinct difference between a delay caused by code execution and a delay caused by setTimeout. In the former case, the browser is busy and likely won't respond to user events (such as clicks) until the executing code has completed. In the latter, any number of JavaScript event threads may execute to completion in the intervening time.

Full Script Source

The complete code for this example includes the artificial delays added to MyApp.q in the render method.

<script type="text/javascript">
YUI().use("node", "transition","async-queue", function (Y) {

var MyApp = {
    NAME : 'Asynchronous Queue Demo',

    q : new Y.AsyncQueue(),

    nodes : {
        root    : null,
        status  : null,
        nav     : null,
        content : null,
        foot    : null
    },

    render : function (container) {
        if (MyApp.nodes.root) {
            MyApp.q.stop();
        }

        // artificial delays have been inserted to simulate _renderNav or
        // _renderContent being process intensive and taking a while to complete
        MyApp.q.add(
            // pass the container param to the callback using Y.bind
            Y.bind(MyApp._renderFramework, MyApp, container),
            {fn: function () {}, timeout: 700}, // artificial delay
            MyApp._renderNav,
            {fn: function () {}, timeout: 700}, // artificial delay
            MyApp._renderContent).run();
    },

    setStatus : function (message,working) {
        MyApp.nodes.status.setHTML(message);

        MyApp.nodes.foot[working?'addClass':'removeClass']('working');
    },

    _renderFramework : function (container) {
        var root = MyApp.nodes.root = Y.one(container);

        root.setHTML(
        '<div class="yui3-module">'+
            '<div class="yui3-hd">'+
                '<h4>'+MyApp.NAME+'</h4>'+
            '</div>'+
            '<div class="yui3-bd">'+
                '<div class="yui3-nav"></div>'+
                '<div class="yui3-content"></div>'+
            '</div>'+
            '<div class="yui3-ft">'+
                '<p class="yui3-status"></p>'+
            '</div>'+
        '</div>');

        MyApp.nodes.status  = root.one('p.yui3-status');
        MyApp.nodes.nav     = root.one('.yui3-nav');
        MyApp.nodes.content = root.one('.yui3-content');
        MyApp.nodes.foot    = root.one('.yui3-ft');

        MyApp.nodes.nav.setStyle('top','-30px');
        MyApp.nodes.content.setStyle('opacity',0);

        MyApp.setStatus('Loading...',true);
    },

    _renderNav : function () {
        var nav = MyApp.nodes.nav;
        nav.append(
            '<ul class="yui3-g">'+
                '<li class="yui3-u-1-4"><a href="#">Nav Lorem</a></li>'+
                '<li class="yui3-u-1-4"><a href="#">Nav Ipsum</a></li>'+
                '<li class="yui3-u-1-4"><a href="#">Nav Dolor</a></li>'+
                '<li class="yui3-u-1-4"><a href="#">Nav Sit</a></li>'+
            '</ul>');

        nav.transition({
            top: 0,
            duration: .3
        });

        // Stub some navigation behavior for the example
        nav.delegate('click', function (e) {
            e.preventDefault();
            MyApp.nodes.content
                .setHTML('<p>Clicked on ' + this.get('text') + '</p>');
        }, 'a');
    },

    _renderContent : function () {
        MyApp.nodes.content
            .setHTML('<p>[ App content here ]</p>')
            .transition({
                opacity: 1,
                duration: .8
            });

        MyApp.setStatus('App initialized',false);
    }
};

Y.one('#init').on('click',function (e) {
    e.preventDefault();
    this.set('text','Re-initialize Application');

    MyApp.render('#demo');
});

// expose the example structure
YUI.example = { MyApp : MyApp };

});
</script>