#

Jump to Table of Contents

# YUI Global Object

The `YUI` module is the core of YUI 3. It must be included on all pages that use YUI, and it's the only dependency required to start writing YUI code. The YUI module contains loader functionality and a dependency calculator, allowing it to serve as a "seed" that can load other dependencies as needed.

## Getting Started

The first step in using YUI is to load the YUI "seed". The seed is the bare minimum core code that's needed to allow YUI to dynamically load additional dependencies on demand. YUI is extremely modular, and the small seed file makes it easy to load only the modules you want to use on a given page.

Include the YUI seed file by adding this script tag to your HTML:

    <script src="http://yui.yahooapis.com/3.10.3/build/yui/yui-min.js"></script>

The seed file adds a single global variable to the page: the `YUI` object. To begin using YUI, you'll first create a new YUI instance and then tell that instance which YUI modules you want to use.

    <div id="demo">Click me</div>
    <script>
    // Create a new YUI sandbox and load the "node" module.
    YUI().use('node', function (Y) {
        // YUI will call this function and pass in the YUI instance (Y) once all
        // modules have finished loading and are ready to use.

        // We can now use Y.Node to get references to DOM elements using CSS
        // selectors.
        var demo = Y.one('#demo');

        // And we can listen for DOM events.
        demo.on('click', function (e) {
            demo.set('text', 'You clicked me!');
        });
    });
    </script>

Calling `YUI()` creates a brand new YUI instance without any active modules. We then call `.use()` on that new instance and pass in a list of modules we want to use, in the form of string parameters. You can name as many modules as you like here. Finally, we pass a callback function that will be executed once all those modules have finished loading. The callback function receives the YUI instance as an argument, which we've named `Y`.

This pattern is called a "sandbox", and it's the most important concept to understand about YUI. It not only makes it easy to load dependencies on demand, it also ensures that your code (and YUI's code!) doesn't pollute the global scope of the page or interfere with other global JavaScript you may be using.

This also means that you can have multiple YUI sandboxes on the same page, and they won't interfere with each other (but they will avoid reloading module code that has already been loaded).

## Alternative Seed Files

In Getting Started, we described the most common way to load YUI using what we call the "Loader Seed". This is a seed file that contains both the core of YUI and the code for the YUI Loader and all the metadata that's necessary to dynamically load additional YUI modules. Depending on your needs, you may want to use a different seed file to further optimize how you load YUI.

### The Base Seed

    <script src="http://yui.yahooapis.com/3.10.3/build/yui-base/yui-base-min.js"></script>

The base seed contains the YUI core and the Get Utility, but doesn't include Loader or any module metadata. The first time you call `YUI().use()`, it will automatically fetch Loader and the module metadata, and then will make a second request to fetch any additional modules you've asked for.

This results in a smaller initial seed file that can speed up the initial page load, but requires more requests overall to get an actual YUI instance up and running. Prior to version 3.4.0, this was the default YUI seed file.

### The Core Seed

    <script src="http://yui.yahooapis.com/3.10.3/build/yui-core/yui-core-min.js"></script>

The core seed contains only the YUI core, and isn't capable of dynamically loading other modules. This is the smallest of all the seed files, but requires you to manually load any dependencies you need before using them.

## Loading Modules

### Dynamic Loading with `use()`

The `use()` method allows you to specify the modules that you want to load into your YUI instance.

    YUI().use('node', 'event', function (Y) {
        // The node and event modules are available on this YUI instance.
    });

YUI modules aren't actually executed until they're used and attached to a YUI instance, and two different YUI instances can have two different sets of modules attached to them. Even if both instances use the same module, each instance gets its own "copy" of that module and isn't affected by changes made in another instance.

    YUI().use('node', function (Y) {
        // We can blow away the Y.Node module in this outer YUI instance...
        Y.Node = null;

        YUI().use('node', function (Y2) {
            // ...without affecting it inside another YUI instance...
            console.log(typeof Y2.Node); // => "function"
        });
    });

You can also call `use()` on an existing YUI instance to attach more modules to that instance without needing to create a completely new YUI instance. This is useful for lazy-loading modules that aren't needed up front.

    // First we create a YUI instance and use the node module.
    YUI().use('calendar', function (Y) {
        // The calendar module is available here.

        // Later, we decide we want to use the autocomplete module, so we attach it
        // to the same instance.
        Y.use('autocomplete', function () {
            // The autocomplete module is available here, and the calendar module is
            // still available as well since this is the same YUI instance.
        });
    });

### Understanding `YUI().use()`

The `YUI().use()` call might seem like magic, but it's actually doing something very simple. It's easier to understand what's going on if we break it into multiple steps.

First, calling `YUI()` creates a brand new YUI instance. This instance will later be passed on to our callback function as the `Y` argument, but if we wanted to, we could just stop here and start using it immediately without even calling `use()`.

Next, we call `use()` on the new YUI instance that was just created. We pass in a list of the modules we want to use, followed by a function that we want YUI to call once all those modules are available.

Finally, YUI loads any necessary modules, attaches them to the YUI instance (this is when the modules are actually executed), and then calls our callback function. The YUI instance passes itself to the callback function as an argument for convenience, so that we don't have to store the instance in a global variable.

The callback function passed to `use()` is executed asynchronously, which means that it doesn't block subsequent code while modules are being loaded.

Broken out into more verbose code, these three steps look like this:

    // Step one: create a new YUI instance.
    var Y = YUI();

    // Step two: load and attach some modules in that instance. Note that we
    // call Y.use() here and not YUI().use().
    Y.use('node', 'event', function (Y) {
        // Step three: do stuff with node and event.

        // The Y object that gets passed to this function is exactly the same as the
        // global Y object created in step one, so it's really only necessary when
        // you don't store the YUI instance in a global variable.
    });

Except for creating a global `Y` variable, that code does exactly the same thing as this code:

    YUI().use('node', 'event', function (Y) {
        // Do stuff with node and event.
    });

If you wanted to, you could create a global `Y` variable using the shorter style as well:

    var Y = YUI().use('node', 'event', function (Y) {
        // Do stuff with node and event.
    });

### Module States

Within any given YUI instance, there are three possible states for a module:

1. Not loaded: The module code has not been downloaded yet and is not available to any YUI instance.

2. Loaded: The module code has been downloaded, but has not been attached to this specific YUI instance. Other instances may be using it, but this instance isn't using it yet.

3. Attached: The module code has been downloaded and is attached to this YUI instance. The module is ready to use.

    /*
        Since we haven't created an instance yet, all YUI modules are
        in the 'Not loaded' state until they are requested.
    */

    YUI().use('calendar', function(Y) {
        //Now calender and all if it's dependencies are 'Loaded' and 'Attached' on this instance
    });

    YUI().use('node', function(Y) {
        //Now node and all of it's dependencies are 'Loaded' and 'Attached' on this instance
        //Calender and it's un-used dependencies are in the 'Loaded' state on this instance
    });

### Static Loading

To reach the "loaded" state, a module's JavaScript just needs to be included on the page after the YUI seed file. The `use()` method will do this for you automatically if necessary, but you could also load a module manually if you wanted to. We call this static loading (since it's the opposite of dynamic loading).

    <script src="http://yui.yahooapis.com/3.10.3/build/yui-base/yui-base-min.js"></script>
    <script src="http://yui.yahooapis.com/3.10.3/build/node-base/node-base-min.js"></script>
    <script>
    YUI().use('node-base', function (Y) {
        // Since the node-base module has already been loaded statically, YUI
        // doesn't need to download it again and can just execute and attach the
        // module code here.
    });
    </script>

If you want to take full manual control of your dependencies, you can statically load any modules you want to use and then pass `'*'` to `use()` instead of specifying a list of module names. This tells YUI to attach all loaded modules to your YUI instance without requiring you to name each module you want to attach.

    YUI().use('*', function(Y) {
        // Any modules that were already loaded on the page statically will now be
        // attached and ready to use. YUI will not automatically load any modules
        // that weren't already on the page.
    });

## Configuring YUI

There are four primary ways to configure YUI and each has its own unique benefits. The YUI object is configured via properties on a simple JavaScript object.

    {
        debug: true,
        combine: true,
        comboBase: 'http://mydomain.com/combo?',
        root: 'yui3/'
    }

A complete list of configuration options is available in the API Docs.

### Instance Config

The most common way to specify config options for YUI is to pass them into the `YUI()` constructor when creating a new instance:

    YUI({
        debug: true,
        combine: true,
        comboBase: 'http://mydomain.com/combo?',
        root: 'yui3/'
    }).use('node', function (Y) {
        // ...
    });

These config options will only apply to this specific instance of YUI.

### YUI_config

By setting options on the global variable `YUI_config`, you can configure every YUI instance on the page even before YUI is loaded.

    YUI_config = {
        debug: true,
        combine: true,
        comboBase: 'http://mydomain.com/combo?',
        root: 'yui3/'
    };

### YUI.GlobalConfig

By setting options on the `YUI.GlobalConfig` object, you can configure every YUI instance on the page after YUI is loaded.

    YUI.GlobalConfig = {
        debug: true,
        combine: true,
        comboBase: 'http://mydomain.com/combo?',
        root: 'yui3/'
    };

### YUI.applyConfig

The global `YUI.applyConfig()` method allows you to configure every YUI instance on the page, but it merges configs passed to it into each instance's existing config. This can be useful if your module is loaded onto the page in a mashup. The other configuration options do not merge, they are simply an object.

    YUI.applyConfig({
        debug: true,
        combine: true
    });
    YUI.applyConfig({
        comboBase: 'http://mydomain.com/combo?',
        root: 'yui3/'
    });

## Creating Custom Modules with `YUI.add()`

`YUI.add()` is a static method that registers a reusable module—essentially, it adds a module to the set of modules available to be attached to a YUI instance via the `use()` method.

Defining a reusable YUI module is as simple as providing a name and a callback function to `YUI.add()`.

    YUI.add('my-module', function (Y) {
       // Write your module code here, and make your module available on the Y
       // object if desired.
       Y.MyModule = {
           sayHello: function () {
               console.log('Hello!');
           }
       };
    });

Note that there are no parentheses after `YUI` when calling `YUI.add()` as there are when calling `YUI().use()`. This is because `add()` is a static method of the global `YUI` object, not a method on a specific YUI instance. Modules are registered globally via `add()` and are later attached to a specific YUI instance via `use()`.

The `add()` method accepts two optional arguments after the callback function: a module version string and a config object. The most useful option in the config object is `requires`, which allows you to specify an array of other YUI modules that your module requires. YUI will then be sure to load these dependencies before executing your module.

    YUI.add('my-module', function (Y) {
       // ...
    }, '0.0.1', {
        requires: ['node', 'event']
    });

After your module has been added via `YUI.add()`, you can specify its name in a `use()` call to attach it to a YUI instance.

    YUI().use('my-module', function (Y) {
        // The Y instance here is the same Y instance that was passed into
        // my-module's add() callback, so the Y.MyModule object that was created
        // there is now available here as well.
        Y.MyModule.sayHello();
    });

A module's `add()` callback isn't executed until that module is attached to a YUI instance via `use()`. Each time a module is attached via `use()`, the module's `add()` callback will be executed, and will receive as an argument the same YUI instance that will later be passed to the `use()` callback.

For more information on creating your custom modules, see our Creating YUI Modules example.

## Using YUI on Node.js

As of version 3.5.0, YUI runs natively on Node.js and comes with an official npm package for easy installation. More information on using YUI on Node.js can be found in the YUI on Node.js guide.

## Loader

Loader's functionality is now built into the YUI Global Object (as long as it's on the page) and puts its power behind the `YUI().use` method.

If you request a module that is not loaded on the page (or a dependency that is not loaded), loader will fetch a copy of that module (and its dependencies) and attach them to your YUI instance.

You can find more information about Loader here.

### New Async Loading in 3.5.0

In `3.5.0`, we introduced asnychronous loading in Loader by default. This means that any script `Loader` injects into the page will be loaded asnychronously. This will decrease load time and improve performance by allowing the browser to fetch as many scripts at once as it can.

If your custom modules are properly wrapped in a `YUI.add` callback, you will see no difference at all. However, if you are loading custom modules that require ordered script loading (depends on another dynamic, unwrapped module), you will need to change your module config to tell `Loader` to not load these modules with the `async` flag. You can do this by adding an `async: false` config to it's module definition and `Y.Get.script` will not load it asynchronously.

    YUI({
        modules: {
            one: {
                async: false,
                fullpath: './one.js'
            },
            two: {
                async: false,
                fullpath: './two.js',
                requires: [ 'one' ]
            }
        }
    }).use('two'), function(Y) {
        //Module one &amp; two are loaded now.
    });

## Y.Lang

`Y.Lang` contains JavaScript language utilities and extensions that are used in the YUI library.

Find more information on `Y.Lang` here.

## Complete Module List

YUI provides more than 250 unique modules to use in your applications. You can view a full list of modules here.