YUI recommends YUI3.
YUI 2 has been deprecated since 2011. This site acts as an archive for files and documentation.
This documentation is no longer maintained.
The YUI Loader Utility is a client-side JavaScript component that allows you to load specific YUI components and their dependencies into your page via script. YUI Loader can operate as a holistic solution by loading all of your necessary YUI components, or it can be used to add one or more components to a page on which some YUI content already exists.
YUI Loader adds value in the following ways:
As you think about how you want to load YUI on the page, you may find it useful to refer to this overview of some of the most common loading strategies and their relative merits:
Note: It's important to emphasize that any client-side loading utility is expected to be somewhat less performant than solutions that write <script>
and <link>
elements directly to the page. The use of dynamic <script>
and <link>
nodes provides good performance and a useful mechanism for bringing in additional JavaScript or CSS after the page has loaded, but for optimal performance you may still wish to write CSS <link>
elements to the head of the page and JavaScript <script>
elements to the bottom of the page during its initial load.
insert()
Method sandbox()
Method addModule
to Add Non-YUI Content with YUI LoaderTo use the YUI Loader Utility, insert its script file into the page. Note that, unlike all other YUI components, the YUI Loader Utility does not require that the Yahoo Global Object be present on the page prior to loading — in fact, the YUI Loader Utility includes the Yahoo Global Object (so you should not load both packages on the same page). The YUI Loader Utility also includes the YUI Get Utility; again, if you are using YUI Loader you should not load Get separately.
<script src="http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js"></script>
Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.
Where these files come from: The files included using the text above will be served from Yahoo! servers. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug
versions of YUI JavaScript files, please download the library distribution and host the files on your own server.
Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.
insert()
MethodYUI Loader makes it a simple thing to get started using YUI components. Place the YUI Loader script on the page, tell it what you want to load, and let it sort out all of the dependencies on your behalf:
<!-- Load the YUI Loader script: --> <script src="http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js"></script>
<!-- Load the YUI Loader script: --> <script src="http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js"></script>
// Instantiate and configure Loader: var loader = new YAHOO.util.YUILoader({ // Identify the components you want to load. Loader will automatically identify // any additional dependencies required for the specified components. require: ["colorpicker", "treeview"], // Configure loader to pull in optional dependencies. For example, animation // is an optional dependency for slider. loadOptional: true, // The function to call when all script/css resources have been loaded onSuccess: function() { //this is your callback function; you can use //this space to call all of your instantiation //logic for the components you just loaded. }, // Configure the Get utility to timeout after 10 seconds for any given node insert timeout: 10000, // Combine YUI files into a single request (per file type) by using the Yahoo! CDN combo service. combine: true }); // Load the files using the insert() method. The insert method takes an optional // configuration object, and in this case we have configured everything in // the constructor, so we don't need to pass anything to insert(). loader.insert();
// Instantiate and configure Loader: var loader = new YAHOO.util.YUILoader({ // Identify the components you want to load. Loader will automatically identify // any additional dependencies required for the specified components. require: ["colorpicker", "treeview"], // Configure loader to pull in optional dependencies. For example, animation // is an optional dependency for slider. loadOptional: true, // The function to call when all script/css resources have been loaded onSuccess: function() { //this is your callback function; you can use //this space to call all of your instantiation //logic for the components you just loaded. }, // Configure the Get utility to timeout after 10 seconds for any given node insert timeout: 10000, // Combine YUI files into a single request (per file type) by using the Yahoo! CDN combo service. combine: true }); // Load the files using the insert() method. The insert method takes an optional // configuration object, and in this case we have configured everything in // the constructor, so we don't need to pass anything to insert(). loader.insert();
In the example above, the YUI Loader script will load from Yahoo servers, calculate the full merged dependency list for the Color Picker and TreeView Controls, load the dependencies on the page by inserting dynamic <link>
and <script>
nodes, and then execute your callback logic (in which you can make use of Color Picker and TreeView).
sandbox()
Method
Different versions of the same library can sometimes conflict with each other. When you insert YUI onto a page that may have another
version of the library on it already, it is sometimes preferable to use a privately-scoped copy of YUI
rather than sharing it globally with the entire page. YUI Loader's sandbox
method provides a way to
do this.
sandbox()
uses the YUI Connection Manager to fetch the script source, evaluates
it inside of an anonymous function, and returns a reference to a well-known local variable that
can be used without risk of having it overwritten by other code on the page. The code that is
evaluated looks like this:
(function() { var YAHOO = [YUI library source]; return YAHOO; })();
(function() { var YAHOO = [YUI library source]; return YAHOO; })();
Setting up a sandbox:
<!-- Load the YUI Loader script: --> <script src="http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js"></script>
<!-- Load the YUI Loader script: --> <script src="http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js"></script>
var loader = new YAHOO.util.YUILoader(); loader.sandbox({ require: ["treeview"], // what to load base: 'http://yui.yahooapis.com/2.9.0/build/', // where on my local domain the library lives loadOptional: true, // pull in optional components // Executed once the sandbox is successfully created onSuccess: function(o) { // o.reference is our sandboxed YAHOO object var ref = o.reference; YAHOO.log("new ref is equal to YAHOO? " + (ref === YAHOO)); // false // TreeView can now be used. Note that YAHOO.widget.TreeView does // *not* exist, because it was included only on the sandboxed YAHOO // object. ref.util.Event.onAvailable("treediv", function() { var tree = new ref.widget.TreeView("treediv"); var n = new ref.widget.TextNode("node 1", tree.getRoot()); new ref.widget.TextNode("node 2", n); new ref.widget.TextNode("node 3", n); tree.draw(); }); }, // Each time a resource is retrieved, onProgress will be executed onProgress: function(o) { log("progress:" + o.name); }, // Executed if the the utility failed to create the sandbox onFailure: function(msg, xhrobj) { var m = "LOAD FAILED: " + msg; // if the failure was from the Connection Manager, the object // returned by that utility will be provided. if (xhrobj) { m += ", " + YAHOO.lang.dump(xhrobj); } YAHOO.log(m); }, // varName: "YAHOO", // What reference should be returned? YAHOO is the default // filter: 'debug' // load the debug version of the library });
var loader = new YAHOO.util.YUILoader(); loader.sandbox({ require: ["treeview"], // what to load base: 'http://yui.yahooapis.com/2.9.0/build/', // where on my local domain the library lives loadOptional: true, // pull in optional components // Executed once the sandbox is successfully created onSuccess: function(o) { // o.reference is our sandboxed YAHOO object var ref = o.reference; YAHOO.log("new ref is equal to YAHOO? " + (ref === YAHOO)); // false // TreeView can now be used. Note that YAHOO.widget.TreeView does // *not* exist, because it was included only on the sandboxed YAHOO // object. ref.util.Event.onAvailable("treediv", function() { var tree = new ref.widget.TreeView("treediv"); var n = new ref.widget.TextNode("node 1", tree.getRoot()); new ref.widget.TextNode("node 2", n); new ref.widget.TextNode("node 3", n); tree.draw(); }); }, // Each time a resource is retrieved, onProgress will be executed onProgress: function(o) { log("progress:" + o.name); }, // Executed if the the utility failed to create the sandbox onFailure: function(msg, xhrobj) { var m = "LOAD FAILED: " + msg; // if the failure was from the Connection Manager, the object // returned by that utility will be provided. if (xhrobj) { m += ", " + YAHOO.lang.dump(xhrobj); } YAHOO.log(m); }, // varName: "YAHOO", // What reference should be returned? YAHOO is the default // filter: 'debug' // load the debug version of the library });
This feature can be used with other JavaScript libraries as long as they conform to a pattern
similiar to YUI's in which all functionality resides within a variable that is not forced into the global namespace (e.g.,
uses var LIBRARY
instead of LIBRARY
or window.LIBRARY
). To sandbox something other
than YUI, use the varName
config to specify the reference that should be returned to the
onSuccess
handler.
Note: since the sandbox
method uses Connection Manager to fetch the script source, it is limited
by the "same origin" domain restrictions common to all XHR connections. To use the sandbox feature, you will
need to serve the YUI files from the domain of the page that will use the sandbox or set up
a proxy on the local domain to fetch the remote resource.
The following configuration options are supported by the YUI Loader Utility.
These can be set in the YUI Loader constructor, set individually on a YUI
Loader instance, or provided to insert()
, calculate()
or sandbox()
:
Configuration Option | Purpose |
---|---|
allowRollup | (boolean) Should Loader use aggregate files (like yahoo-dom-event.js or utilities.js ) that combine several YUI components in a single HTTP request? Default: true. |
base | (string) Allows you to specify a different location (as a full or relative filepath) for the YUI build directory. By default, YUI Loader will serve files from Yahoo's servers. |
charset | (string) The charset attribute for inserted nodes. |
combine | (boolean) If set to true, YUI files will be combined into a single request using the combo service provided on the Yahoo! CDN |
comboBase | (string) The base path to the Yahoo! CDN service. Ex: http://yui.yahooapis.com/combo? |
data | (any) Data payload that will be provided to all callbacks. |
filter |
(string or object) A filter to apply to result urls. This filter will modify the default
path for all modules. The default path for the YUI library is the
minified version of the files (e.g., event-min.js). The filter property
can be a predefined filter or a custom filter. The valid predefined
filters are:
myFilter: { 'searchExp': "-min\\.js", 'replaceStr': "-debug.js" } |
force | (array) A list of modules that should always be loaded when required, even if already present on the page |
ignore | (array) A list of modules that should never be dynamically loaded. |
insertBefore | (HTMLElement or string) Node or id for a node that should be used as the insertion point for new nodes. |
loadOptional | (boolean) Should loader load optional dependencies for the components you're requesting? (Note: If you only want some but not all optional dependencies, you can list out the dependencies you want as part of your required list.) Default: false. |
onSuccess | (function) The code you want to run once your required YUI components are fully loaded. |
onFailure | (function) The code you want to run if the insert fails. |
onProgress | (function) The code to execute each time an individual module is loaded. |
onTimeout | (function) The code to execute if the Get utility detects a timeout. |
require (method) | (array) Sets the list of YUI components that you require. Each member of an array should be a string referencing the component's module name. The list of module names for YUI components is listed below. This is a property if passed in the configuration, but it is a method on an instance. Each subsequent call to require appends the new requirements rather than overwriting the old ones. |
root | (string) The root path to prepend to module names for the combo service. Ex: 2.5.2/build/. |
scope | (object) The execution context for all callbacks. |
skin | (object) Configures default skin for added components and allows specification of additional or override skins for specific components. See the skinning section below for more details. By default, YUI Loader will set skin-sam as the default skin for loaded components. |
varName | (string) For loading non-YUI scripts: This is the name of a variable that
the utility will poll for in order to determine when the script is loaded. This is
necessary in order to support loading non-YUI scripts in Safari 2.x. For sandbox() : specifies the name of a
variable that should be present once the sandboxed script is available. A
reference to this variable will be returned to the onSuccess
handler (the reference field) |
YUI as of version 2.3.0 moved to a skinning model for controlling the presentation of UI controls. With that release, a default skin, sam
, was introduced. By default, YUI Loader will bring in the sam
assets for any YUI component you require for which a skin exists.
As we go forward, the YUI ecosystem will grow to support a number of different skins for various components. As this occurs, you'll want to be able to specify which skin you wish to use for a given component. YUI Loader allows you to specify both a global default skin (which defaults to sam
unless you specify otherwise) and one or more alternative skins for each component you require. You control this using the skin
property of your Loader instance.
Returning to our simple use case, here's how we might configure TreeView to use an alternative skin, myTVSkin
, and Color Picker to use a skin called myCPSkin
.
<!-- Load the YUI Loader script: --> <script src="http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js"></script>
<!-- Load the YUI Loader script: --> <script src="http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js"></script>
loader = new YAHOO.util.YUILoader({ require: ["colorpicker", "treeview"], //Set your skins member here: skin: { // Specifies the location of the skin relative to the build // directory for the skinnable component. base: 'assets/skins/', // The default skin, which is automatically applied if not // overriden by a component-specific skin definition. // Change this in to apply a different skin globally defaultSkin: 'sam', // Any component-specific overrides can be specified here, // making it possible to load different skins for different // components. It is possible to load more than one skin // for a given component as well. overrides: { colorpicker: ['myCPSkin'], treeview: ['myTVSkin'] } }, onSuccess: function(o) { //callback logic goes here } }); loader.insert();
loader = new YAHOO.util.YUILoader({ require: ["colorpicker", "treeview"], //Set your skins member here: skin: { // Specifies the location of the skin relative to the build // directory for the skinnable component. base: 'assets/skins/', // The default skin, which is automatically applied if not // overriden by a component-specific skin definition. // Change this in to apply a different skin globally defaultSkin: 'sam', // Any component-specific overrides can be specified here, // making it possible to load different skins for different // components. It is possible to load more than one skin // for a given component as well. overrides: { colorpicker: ['myCPSkin'], treeview: ['myTVSkin'] } }, onSuccess: function(o) { //callback logic goes here } }); loader.insert();
Much more information about skinning and creating custom skins can be found in the article entitled "Skinning YUI."
addModule
to Add Non-YUI Content with YUI LoaderYUI Loader knows all YUI components and their required and optional dependencies. When you build applications on top of YUI, you can tell YUI Loader about your own custom components and their dependencies as well using YUI Loader's addModule
method.
addModule
is called from a YUI Loader instance and takes as its argument a configuration object that defines the metadata associated with the module you are adding. The configuration object's members include:
Member (type) | Description |
---|---|
name (string) | The unique module name for this component; must not match any YUI module name nor any other module name you've used within the current page. |
type (string) | The type of resource comprised by this component; must be either "js" or "css". |
path (string) | The path to the file; will be concatenated with the base path if you've defined a base configuration in your YUI Loader instance. This path should include the filename itself (e.g. "json/json-min.js"). |
fullpath (string) | Overrides path if path is defined and is used as a full URI to the component's source file (e.g. "http://www.json.org/json.js"). |
requires (array) | An array of module names designating required dependencies for this component; can be mixture of YUI and custom components (e.g. ['yahoo', 'dom', 'event'] ). |
optional (array) | An array of module names designating optional dependencies for this component; can be mixture of YUI and custom components (e.g. ['animation', 'dragdrop'] ). |
after (array) | An array of module names that are not dependencies, but need to be included above this component if they are present. |
varName (s) | A variable that will be available once an external script reference is fully loaded. |
//Add the module to YUILoader loader.addModule({ name: "json", //module name; must be unique type: "js", //can be "js" or "css" fullpath: "http://www.json.org/json2.js", //can use a path instead, extending base path varName: "JSON" // a variable that will be available when the script is loaded. Needed // in order to act on the script immediately in Safari 2.x and below. //requires: ['yahoo', 'event'] //if this module had dependencies, we could define here });
//Add the module to YUILoader loader.addModule({ name: "json", //module name; must be unique type: "js", //can be "js" or "css" fullpath: "http://www.json.org/json2.js", //can use a path instead, extending base path varName: "JSON" // a variable that will be available when the script is loaded. Needed // in order to act on the script immediately in Safari 2.x and below. //requires: ['yahoo', 'event'] //if this module had dependencies, we could define here });
When loading external scripts that you do not control, specify a varName
property. YUI Loader will determine when the script is fully loaded by polling for this property. This is only needed in order to support external scripts in Safari 2.x. All other A-Grade browsers will work correctly without specifying a varName
.
See the addModule
example and its accompanying tutorial for more information about using varName
properties.
When you do control the the content, and when that content is meant to be used with YUI, the best way to notify YUI Loader that loading is complete is to use the YAHOO.register
method. YAHOO.register
is the same method that YUI components use to register themselves with the YAHOO
object and record information about themselves in the YAHOO.env
registry.
YAHOO.register
takes three arguments:
YAHOO.util.Anim
would be the core class for the Animation Utility);For example, the Animation Utility in version 2.2.2 registered itself with the following code:
YAHOO.register("animation", YAHOO.util.Anim, { version: "2.9.0", build: "204" });
YAHOO.register("animation", YAHOO.util.Anim, { version: "2.9.0", build: "204" });
Reminder: Use of YAHOO.register
obviates the need for a varName
property when loading external scripts.
In version 2.4.1 of the YUILoader, defining modules that override existing YUI skins requires that you load them in two phases: 1) The YUI component, 2) The custom component:
// first load treeview new YAHOO.util.YUILoader({ require: ['treeview'], onSuccess: function() { // when treeview is finished loading, define and load the custom tree modules var loader = new YAHOO.util.YUILoader(); // define the css module that overrides the default treeview css loader.addModule({ name:'customtreecss', type:'css', fullpath:'http://domain/customtree.css', requires:['treeview'] }); // define the script module that extends treeview loader.addModule({ name:'customtree', type:'js', fullpath:'http://domain/customtree.js', // make the css file a requirement for the script requires:['customtreecss'] }); loader.onSuccess = function() { // build the custom tree }; loader.insert(); } }).insert(); // insert the treeview component immediately
// first load treeview new YAHOO.util.YUILoader({ require: ['treeview'], onSuccess: function() { // when treeview is finished loading, define and load the custom tree modules var loader = new YAHOO.util.YUILoader(); // define the css module that overrides the default treeview css loader.addModule({ name:'customtreecss', type:'css', fullpath:'http://domain/customtree.css', requires:['treeview'] }); // define the script module that extends treeview loader.addModule({ name:'customtree', type:'js', fullpath:'http://domain/customtree.js', // make the css file a requirement for the script requires:['customtreecss'] }); loader.onSuccess = function() { // build the custom tree }; loader.insert(); } }).insert(); // insert the treeview component immediately
Each YUI component has a corresponding module name that is used as a unique identifier within YUI scripts. For example, the Event Utility is internally referred to as "event"
. YUI Loader loads components based on these unique module names. Here is the full list of YUI module names. All except YUI Loader itself can be loaded via the Loader component.
YUI ships with some aggregate or "rollup" files, each comprising two or more modules, to help you reduce the number of HTTP requests you make while loading YUI content. Each aggregate file has its own module name.
Moreover, some modules provide the functionality of one or more modules in the above list — for example, YUI Loader includes the Get Utility.
When you choose to allowRollup
s, YUI Loader will choose the most appropriate set of files to meet your requirements while using the smallest number of included files. You can also specify an aggregate file directly as a requirement by requesting it by its own module name. The following is a list of modules that aggregate or include multiple modules:
YUI Rollup | Provides |
---|---|
container | containercore |
editor | simpleeditor |
reset-fonts | reset, fonts |
reset-fonts-grids | reset, fonts, grids, reset-fonts |
utilities | yahoo, event, dragdrop, animation, dom, connection, element, get, yuiloader, yahoo-dom-event |
yahoo-dom-event | yahoo, dom, event |
yuiloader | yahoo, get |
yuiloader-dom-event | yahoo, dom, event, get, yuiloader, yahoo-dom-event |
YUI Loader's API changed, and its implementation simplified in the 2.4.0 release. 2.3.x implementations
that use YAHOO.util.YUILoader
instances will require changing the onLoadComplete
property
to onSuccess
. YAHOO_config
is no longer supported for loading YUI components. Implementations
that used YAHOO_config
will need to be reworked to use a YAHOO.util.YUILoader
instance.
The verifier
function is no longer supported for loading external scripts. Instead you must specify a varName
property to support Safari 2.x when the script doesn't use YUI's register functionality.
If you are attempting to implement a version of YUI Loader earlier than 2.4.0, refer to the API documentation and examples in the distribution for that release. Older releases are archived on YUILibrary.com.
Unlike other properties, the filter property can't be set directly on an instance. It must be set by passing a configuration object to either the YUILoader constructor or the insert/sandbox method.
In 2.4.1 Defining custom modules that override existing YUI skins requires a specific syntax. See the addModule section for details.
About this Section: YUI generally works well with mobile browsers that are based on A-Grade browser foundations. For example, Nokia's N-series phones, including the N95, use a browser based on Webkit — the same foundation shared by Apple's Safari browser, which is found on the iPhone. The fundamental challenges in developing for this emerging class of full, A-Grade-derived browsers on handheld devices are:
There are other considerations, many of them device/browser specific (for example, current versions of the iPhone's Safari browser do not support Flash). The goal of these sections on YUI User's Guides is to provide you some preliminary insights about how specific components perform on this emerging class of mobile devices. Although we have not done exhaustive testing, and although these browsers are revving quickly and present a moving target, our goal is to provide some early, provisional advice to help you get started as you contemplate how your YUI-based application will render in the mobile world.
More Information:
The YUI Loader is fully supported on Apple's iPhone and the Nokia N-Series browsers; you can expect it to perform identically on those browsers relative to the supported A-Grade browsers.
The YUI Library and related topics are discussed on the on the YUILibrary.com forums.
Also be sure to check out YUIBlog for updates and articles about the YUI Library written by the library's developers.
The YUI Library's public bug tracking and feature request repositories are located on the YUILibrary.com site. Before filing new feature requests or bug reports, please review our reporting guidelines.
All YUI 2.x users should review the YUI 2.8.2 security bulletin, which discusses a vulnerability present in YUI 2.4.0-2.8.1.
Copyright © 2013 Yahoo! Inc. All rights reserved.