Thursday, March 6, 2014

jQuery UI: Pre-loading Remote Tab Content

The tabs widget can support remote content just as well as it does local div elements. All we have do is point the href attribute to some remote HTML that we want rendered when that tab is activated. The widget is smart enough to understand that we're referencing a URI, and not a local DOM ID. The content, for any given tab referencing remote content, is loaded when the tab is selected. Not before. However, this content is cached, so the second time the user selects a tab with remote content, it'll render instantly. There's a pre-loading trick you can use to give the perception of even faster loading time.

This example illustrates how to pre-load remote tab content. When the tabs are first displayed, typically the first tab is active by default. This means that the rest of them are just sitting there doing nothing. Why not load their content during the second or two the user is parsing the default active tab? Here's what that code looks like.

    create: function( e, ui ) {
        var $div = $( this ),
            $tabs = $div.find( "li" )
                .not( );
        $tabs.each( function() {
            $div.tabs( "load", $( this ).index() );

As you can see, we're creating the tabs instance as we normally would, and we're passing it a create event handler. The create event is triggered as soon as the instance is constructed. This handler finds all the tabs that aren't currently active — all the li elements that aren't — and stores them in the $tabs variable. The reason we don't want included is because it's the tab that's currently displayed, and we don't need to pre-load it. Next, we call the load() method on each of the indexes that aren't displayed.

You'll notice in the example that the mock content has some delayed response times. For example, tab 3 takes 800 milliseconds to respond. You notice the latency when the content isn't pre-loaded, but with this example, you don't notice any latency.

No comments :

Post a Comment