YUI 3.x Home -

Site Search (YDN & YUIBlog):

# YUI Library Examples: The YUI Global Object: YUI Loader - Dynamically Adding YUI and External Modules

## The YUI Global Object: YUI Loader - Dynamically Adding YUI and External Modules

This example uses the dynamic loading capability built into YUI to pull in additional components as needed. In addition, it demonstrates how to define external modules that can be loaded alongside YUI.

This example works as follows:

1. A `YUI` instance is created with a configuration object that defines parameters we need to dynamically load new modules.
2. `node` is used so that we can bind an event listener to a button. YUI will dynamically fetch `node` and its dependencies. By default, these dependencies will be fetched from the Yahoo! CDN and will be combined into a single file.
3. A click listener is added to a button.
4. When this button is clicked, YUI will dynamically fetch 3.x Drag & Drop and 2.x Calendar files. The CSS file will be fetched first; this helps prevent a flash of unstyled content when the Calendar Control is loaded. This file is inserted above a style block which contains our custom calendar styles (via a YUI config option) so that styles are applied in the correct order.
5. A Calendar instance is created, and it is made draggable.

View example in new window.

### Creating your YUI instance

First, we need to create our YUI instance with the `node` module, so we can attach a listener to a button.

    YUI().use('node', function(Y) { });

    YUI().use('node', function(Y) {

    });

YUI().use('node', function(Y) { });

YUI accepts a configuration object when you create an instance. Your dynamic-loading options can be defined here.

    YUI({    // We can specify a node that is the insertion point for all new nodes.  This    // is useful for making sure css rules are applied in the correct order.    insertBefore: 'styleoverrides',     // This lets you define one or more external modules that will be added to    // the YUI metadata.  You can define dependency relationships between your    // modules and also between your modules and YUI modules.  Here we are    // defining 2.x calendar components as external modules.  See    // <a href="http://developer.yahoo.com/yui/3/api/Loader.html#method_addModule">    // the API docs</a> for a complete list of module configuration options.     // Defines a list of groups.  The modules in each group group share the     // base path and combo specification.    groups: {        yui2: {            combine: true,            base: 'http://yui.yahooapis.com/2.8.0r4/build/',            comboBase: 'http://yui.yahooapis.com/combo?',            root: '2.8.0r4/build/',            modules:  {                yui2_yde: {                    path: 'yahoo-dom-event/yahoo-dom-event.js'                },                yui2_calendar: {                    path: 'calendar/calendar-min.js',                    requires: ['yui2_yde', 'yui2_calendarcss']                },                yui2_calendarcss: {                    path: 'calendar/assets/skins/sam/calendar.css',                    type: 'css'                }            }        }    } }).use('node', function(Y) { });

    YUI({
        // We can specify a node that is the insertion point for all new nodes.  This
        // is useful for making sure css rules are applied in the correct order.
        insertBefore: 'styleoverrides',

        // This lets you define one or more external modules that will be added to
        // the YUI metadata.  You can define dependency relationships between your
        // modules and also between your modules and YUI modules.  Here we are
        // defining 2.x calendar components as external modules.  See
        // <a href="http://developer.yahoo.com/yui/3/api/Loader.html#method_addModule">
        // the API docs</a> for a complete list of module configuration options.

        // Defines a list of groups.  The modules in each group group share the
        // base path and combo specification.
        groups: {
            yui2: {
                combine: true,
                base: 'http://yui.yahooapis.com/2.8.0r4/build/',
                comboBase: 'http://yui.yahooapis.com/combo?',
                root: '2.8.0r4/build/',
                modules:  {
                    yui2_yde: {
                        path: 'yahoo-dom-event/yahoo-dom-event.js'
                    },
                    yui2_calendar: {
                        path: 'calendar/calendar-min.js',
                        requires: ['yui2_yde', 'yui2_calendarcss']
                    },
                    yui2_calendarcss: {
                        path: 'calendar/assets/skins/sam/calendar.css',
                        type: 'css'
                    }
                }
            }
        }

    }).use('node', function(Y) {

    });

YUI({ // We can specify a node that is the insertion point for all new nodes. This // is useful for making sure css rules are applied in the correct order. insertBefore: 'styleoverrides', // This lets you define one or more external modules that will be added to // the YUI metadata. You can define dependency relationships between your // modules and also between your modules and YUI modules. Here we are // defining 2.x calendar components as external modules. See // <a href="http://developer.yahoo.com/yui/3/api/Loader.html#method_addModule"> // the API docs</a> for a complete list of module configuration options. // Defines a list of groups. The modules in each group group share the // base path and combo specification. groups: { yui2: { combine: true, base: 'http://yui.yahooapis.com/2.8.0r4/build/', comboBase: 'http://yui.yahooapis.com/combo?', root: '2.8.0r4/build/', modules: { yui2_yde: { path: 'yahoo-dom-event/yahoo-dom-event.js' }, yui2_calendar: { path: 'calendar/calendar-min.js', requires: ['yui2_yde', 'yui2_calendarcss'] }, yui2_calendarcss: { path: 'calendar/assets/skins/sam/calendar.css', type: 'css' } } } } }).use('node', function(Y) { });

### Creating the Calendar

Now that we have our core YUI instance in place, we add an event listener to a button that will dynamically load YUI 3.x Drag & Drop and YUI 2.x Calendar.

    // The callback supplied to use() will be executed regardless of// whether the operation was successful or not.  The second parameter// is a result object that has the status of the operation.  We can// use this to try to recover from failures or timeouts.if (!result.success) {     Y.log('Load failure: ' + result.msg, 'warn', 'Example'); } else {     // Add a button click listener to load the calendar    var handle = Y.on('click', function(e) {         // dynamically load the 2.x calendar and 3.x drag and drop        Y.use('dd-drag', 'yui2_calendar', function(Y) {            var cal1 = new YAHOO.widget.Calendar('cal1', 'cal1Cont');             // Once the 2.x calendar renders, we will add 3.x drag            // functionality t0 it.            cal1.renderEvent.subscribe(function() {                var dd = new Y.DD.Drag({                    node: '#cal1Cont'                }).addHandle('div.calheader');            });            cal1.render();        });         // Remove the button click listener so that we only try to        // load the calendar control once.        handle.detach();     }, '#button1');}

    // The callback supplied to use() will be executed regardless of
    // whether the operation was successful or not.  The second parameter
    // is a result object that has the status of the operation.  We can
    // use this to try to recover from failures or timeouts.
    if (!result.success) {

        Y.log('Load failure: ' + result.msg, 'warn', 'Example');

    } else {

        // Add a button click listener to load the calendar
        var handle = Y.on('click', function(e) {

            // dynamically load the 2.x calendar and 3.x drag and drop
            Y.use('dd-drag', 'yui2_calendar', function(Y) {
                var cal1 = new YAHOO.widget.Calendar('cal1', 'cal1Cont');

                // Once the 2.x calendar renders, we will add 3.x drag
                // functionality t0 it.
                cal1.renderEvent.subscribe(function() {
                    var dd = new Y.DD.Drag({
                        node: '#cal1Cont'
                    }).addHandle('div.calheader');
                });
                cal1.render();
            });

            // Remove the button click listener so that we only try to
            // load the calendar control once.
            handle.detach();

        }, '#button1');
    }

// The callback supplied to use() will be executed regardless of // whether the operation was successful or not. The second parameter // is a result object that has the status of the operation. We can // use this to try to recover from failures or timeouts. if (!result.success) { Y.log('Load failure: ' + result.msg, 'warn', 'Example'); } else { // Add a button click listener to load the calendar var handle = Y.on('click', function(e) { // dynamically load the 2.x calendar and 3.x drag and drop Y.use('dd-drag', 'yui2_calendar', function(Y) { var cal1 = new YAHOO.widget.Calendar('cal1', 'cal1Cont'); // Once the 2.x calendar renders, we will add 3.x drag // functionality t0 it. cal1.renderEvent.subscribe(function() { var dd = new Y.DD.Drag({ node: '#cal1Cont' }).addHandle('div.calheader'); }); cal1.render(); }); // Remove the button click listener so that we only try to // load the calendar control once. handle.detach(); }, '#button1'); }

### Full source

    <input id="button1" type="button" value="Click to load YUI Calendar" class="button" /> <div id="cal1Cont"></div> <script> YUI({     // We can specify a node that is the insertion point for all new nodes.  This    // is useful for making sure css rules are applied in the correct order.    insertBefore: 'styleoverrides',     // This lets you define one or more external modules that will be added to    // the YUI metadata.  You can define dependency relationships between your    // modules and also between your modules and YUI modules.  Here we are    // defining 2.x calendar components as external modules.  See    // <a href="http://developer.yahoo.com/3.x/api/Loader.html#method_addModule">    // the API docs</a> for a complete list of module configuration options.     // Defines a list of groups.  The modules in each group group share the     // base path and combo specification.    groups: {        yui2: {            combine: true,            base: 'http://yui.yahooapis.com/2.8.0r4/build/',            comboBase: 'http://yui.yahooapis.com/combo?',            root: '2.8.0r4/build/',            modules:  {                yui2_yde: {                    path: 'yahoo-dom-event/yahoo-dom-event.js'                },                yui2_calendar: {                    path: 'calendar/calendar-min.js',                    requires: ['yui2_yde', 'yui2_calendarcss']                },                yui2_calendarcss: {                    path: 'calendar/assets/skins/sam/calendar.css',                    type: 'css'                }            }        }    }     // Specifies whether or not optional dependencies should be loaded    // loadOptional: true,     // By default, the minified versions of the files are loaded.  We can specify    // 'debug' to load versions with log statements, or 'raw' to load a version    // that isn't minified, but has log statements stripped.    filter: 'debug',     // Give up if any single node request takes more than 10 seconds.    timeout: 10000 // 3.x node will be dynamically loaded so we can work with DOM elements}).use('node', function(Y, result) {     // The callback supplied to use() will be executed regardless of    // whether the operation was successful or not.  The second parameter    // is a result object that has the status of the operation.  We can    // use this to try to recover from failures or timeouts.    if (!result.success) {         Y.log('Load failure: ' + result.msg, 'warn', 'Example');     } else {         // Add a button click listener to load the calendar        var handle = Y.on('click', function(e) {             // dynamically load the 2.x calendar and 3.x drag and drop            Y.use('dd-drag', 'yui2-calendar', function(Y) {                var cal1 = new YAHOO.widget.Calendar('cal1', 'cal1Cont');                 // Once the 2.x calendar renders, we will add 3.x drag                // functionality to it.                cal1.renderEvent.subscribe(function() {                    var dd = new Y.DD.Drag({                        node: '#cal1Cont'                    }).addHandle('div.calheader');                });                cal1.render();            });             // Remove the button click listener so that we only try to            // load the calendar control once.            handle.detach();         }, '#button1');    }  });</script>

    <input id="button1" type="button" value="Click to load YUI Calendar" class="button" />

    <div id="cal1Cont"></div>

    <script>

    YUI({

        // We can specify a node that is the insertion point for all new nodes.  This
        // is useful for making sure css rules are applied in the correct order.
        insertBefore: 'styleoverrides',

        // This lets you define one or more external modules that will be added to
        // the YUI metadata.  You can define dependency relationships between your
        // modules and also between your modules and YUI modules.  Here we are
        // defining 2.x calendar components as external modules.  See
        // <a href="http://developer.yahoo.com/3.x/api/Loader.html#method_addModule">
        // the API docs</a> for a complete list of module configuration options.

        // Defines a list of groups.  The modules in each group group share the
        // base path and combo specification.
        groups: {
            yui2: {
                combine: true,
                base: 'http://yui.yahooapis.com/2.8.0r4/build/',
                comboBase: 'http://yui.yahooapis.com/combo?',
                root: '2.8.0r4/build/',
                modules:  {
                    yui2_yde: {
                        path: 'yahoo-dom-event/yahoo-dom-event.js'
                    },
                    yui2_calendar: {
                        path: 'calendar/calendar-min.js',
                        requires: ['yui2_yde', 'yui2_calendarcss']
                    },
                    yui2_calendarcss: {
                        path: 'calendar/assets/skins/sam/calendar.css',
                        type: 'css'
                    }
                }
            }
        }

        // Specifies whether or not optional dependencies should be loaded
        // loadOptional: true,

        // By default, the minified versions of the files are loaded.  We can specify
        // 'debug' to load versions with log statements, or 'raw' to load a version
        // that isn't minified, but has log statements stripped.
        filter: 'debug',

        // Give up if any single node request takes more than 10 seconds.
        timeout: 10000

    // 3.x node will be dynamically loaded so we can work with DOM elements
    }).use('node', function(Y, result) {

        // The callback supplied to use() will be executed regardless of
        // whether the operation was successful or not.  The second parameter
        // is a result object that has the status of the operation.  We can
        // use this to try to recover from failures or timeouts.
        if (!result.success) {

            Y.log('Load failure: ' + result.msg, 'warn', 'Example');

        } else {

            // Add a button click listener to load the calendar
            var handle = Y.on('click', function(e) {

                // dynamically load the 2.x calendar and 3.x drag and drop
                Y.use('dd-drag', 'yui2-calendar', function(Y) {
                    var cal1 = new YAHOO.widget.Calendar('cal1', 'cal1Cont');

                    // Once the 2.x calendar renders, we will add 3.x drag
                    // functionality to it.
                    cal1.renderEvent.subscribe(function() {
                        var dd = new Y.DD.Drag({
                            node: '#cal1Cont'
                        }).addHandle('div.calheader');
                    });
                    cal1.render();
                });

                // Remove the button click listener so that we only try to
                // load the calendar control once.
                handle.detach();

            }, '#button1');
        }

    });
    </script>

<input id="button1" type="button" value="Click to load YUI Calendar" class="button" /> <div id="cal1Cont"></div> <script> YUI({ // We can specify a node that is the insertion point for all new nodes. This // is useful for making sure css rules are applied in the correct order. insertBefore: 'styleoverrides', // This lets you define one or more external modules that will be added to // the YUI metadata. You can define dependency relationships between your // modules and also between your modules and YUI modules. Here we are // defining 2.x calendar components as external modules. See // <a href="http://developer.yahoo.com/3.x/api/Loader.html#method_addModule"> // the API docs</a> for a complete list of module configuration options. // Defines a list of groups. The modules in each group group share the // base path and combo specification. groups: { yui2: { combine: true, base: 'http://yui.yahooapis.com/2.8.0r4/build/', comboBase: 'http://yui.yahooapis.com/combo?', root: '2.8.0r4/build/', modules: { yui2_yde: { path: 'yahoo-dom-event/yahoo-dom-event.js' }, yui2_calendar: { path: 'calendar/calendar-min.js', requires: ['yui2_yde', 'yui2_calendarcss'] }, yui2_calendarcss: { path: 'calendar/assets/skins/sam/calendar.css', type: 'css' } } } } // Specifies whether or not optional dependencies should be loaded // loadOptional: true, // By default, the minified versions of the files are loaded. We can specify // 'debug' to load versions with log statements, or 'raw' to load a version // that isn't minified, but has log statements stripped. filter: 'debug', // Give up if any single node request takes more than 10 seconds. timeout: 10000 // 3.x node will be dynamically loaded so we can work with DOM elements }).use('node', function(Y, result) { // The callback supplied to use() will be executed regardless of // whether the operation was successful or not. The second parameter // is a result object that has the status of the operation. We can // use this to try to recover from failures or timeouts. if (!result.success) { Y.log('Load failure: ' + result.msg, 'warn', 'Example'); } else { // Add a button click listener to load the calendar var handle = Y.on('click', function(e) { // dynamically load the 2.x calendar and 3.x drag and drop Y.use('dd-drag', 'yui2-calendar', function(Y) { var cal1 = new YAHOO.widget.Calendar('cal1', 'cal1Cont'); // Once the 2.x calendar renders, we will add 3.x drag // functionality to it. cal1.renderEvent.subscribe(function() { var dd = new Y.DD.Drag({ node: '#cal1Cont' }).addHandle('div.calheader'); }); cal1.render(); }); // Remove the button click listener so that we only try to // load the calendar control once. handle.detach(); }, '#button1'); } }); </script>

Copyright © 2010 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings