YUI 3: Get

The Get Utility provides a mechanism for attaching script and css resources — including cross-domain resources — to the DOM after the page has loaded.

There are two common use cases for the Get Utility:

  1. Cross-site data retrieval: Because XMLHttpRequest (and YUI IO Utility, which uses XMLHttpRequest) adheres to a strict same-origin policy, the retrieval of third-party data via XHR requires a server-side proxy. Where you control or absolutely trust a cross-domain source, you can eliminate the server-side proxy by loading a script file directly from the external domain; that script file, which would typically contain JSON-formatted data, is executed immediately upon load. It is crucial to understand that if there is malicious code present in the loaded script there is no safe way to innoculate your users from that malicious code...the browser will execute the code with full privileges. Never expose your users to JavaScript whose source is not absolutely trustworthy.
  2. Progressive loading of functionality: In rich web applications, it's often useful to load some script and CSS resources only when they become necessary (based on user action). The Get Utility provides a flexible mechanism for bringing additional resources on-demand. (Note: If you're loading YUI resources specifically, use the YUI Loader Utility; the YUI Loader employs the Get Utility under the hood to bring in YUI components and has an intrinsic understanding of the YUI dependency tree.)

What Is the Difference Between the Get Utility and the IO Utility?

The Get Utility inserts new content into a window by creating new nodes and supplying a src attribute. Files inserted into the window in this manner are processed (and, in the case of scripts, executed) immediately upon load. While querystring parameters can be passed in the src attribute URL, no data can be sent to the server via HTTP POST using this method. The Get Utility can only make HTTP GET requests. It can, however, interact with disparate domains. As noted above, the Get Utility is ideal for loading your own scripts or CSS progressively (lazy-loading) or for retrieving cross-domain JSON data from sources in which you have total trust.

The YUI IO Utility, by contrast, uses the XMLHttpRequest object to interact with the server. XMLHttpRequest is limited by a strict same origin policy, but it supports a greater range of HTTP methods (including POST). Moreover, script data retrieved via XMLHttpRequest can be validated on the server side or in JavaScript (using, for example, the JSON Utility) prior to being executed. As a result, IO Utility is a more appropriate choice for rich two-way communication between browser and server and gives you more control over data before it's processed within the browser.

Version 3.0 of the IO Utility now supports cross domain requests. There are specific trust requirements as described in documentation for the IO Utility. This may be a better choice if the service you are accessing can be configured to trust the server that is hosting your application.

Getting Started

The Get Utility is included in the default YUI bundle: the YUI Global Object. To use the Get Utility, include the YUI seed file:

  1. <script src="http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js"></script>;
  2.  
<script src="http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js"></script>;
 

With the Get Utility present, you can make use of it to fetch script (Y.Get.script()) and/or CSS (Y.Get.css()) resources to the page. The script and css methods each take the following arguments:

  1. URL(s): A string or an array of strings designating the URL(s) you wish to load into the page;
  2. options: An optional object containing configuration information for the transaction; see the Configuring a Get Utility Transaction section below for the full list of configuraton members you can include here.

A sample request for a file might look like this:

  1. var Y = YUI();
  2. var objTransaction = Y.Get.script("http://json.org/json.js", {
  3. onSuccess: function() {
  4. alert("file loaded");
  5. });
  6.  
  7. //objTransaction will be an object with a single field, tId,
  8. //which is a unique identifier of the transaction following the pattern
  9. //"q0", "q1", "q2"..."qn".
  10.  
var Y = YUI();
var objTransaction = Y.Get.script("http://json.org/json.js", {
    onSuccess: function() {
	alert("file loaded");
});
 
//objTransaction will be an object with a single field, tId, 
//which is a unique identifier of the transaction following the pattern
//"q0", "q1", "q2"..."qn".
 

Configuring a Get Utility Transaction

The Get Utility is configured via the second argument to the script or css method. This optional argument comprises an object containing one or more of the following fields:

Configuration Option Purpose
onSuccess (function) Callback method invoked by Get Utility when the requested file(s) have loaded successfully.
onFailure (function) Callback method invoked by Get Utility when an error is detected or abort is called.
onProgress (function) Callback method invoked by Get Utility after each node is inserted.
onTimeout (function) Callback method invoked by Get Utility if a timeout is detected.
onEnd (function) Callback method invoked by Get Utility when a transaction completes no matter how the transaction ended.
attributes (object) A hash of attributes to apply to the dynamically created nodes. You might use this to add media="print" to a css file, for example.
win (obj) The window into which the loaded resource(s) will be inserted. Default: the current window.
scope (object) The execution scope in which the onSuccess or onFailure callback will run. Default: the current window.
data (any) Data to pass as an argument to onSuccess or onFailure callbacks. Default: null.
autopurge (boolean) If set to true, script nodes will automatically be removed every 20 transactions (this number is globally configurable via the Y.Get.PURGE_THRESH property); script nodes can be safely removed in most cases, as their contents (having executed) remain available. CSS nodes should not have this set to true as it will remove the CSS rules. Default: true for script nodes, false for CSS nodes.
timeout (int) Number of milliseconds to wait for a script to finish loading before timing out

Making Use of Arguments Supplied to Your Callback

As noted in the section above, your callback method (whether onSuccess or onFailure) will have access to the data member supplied in the configuration object, assuming you provided one. But the data member is just one of several fields included in the object passed to your callback. Here's a summary of the fields contained in that argument object:

Field Contents
tId (string) The unique identifier for this transaction; this string is available as the tId member of the object returned to you upon calling the script or css method.
data (any) The data field you passed in your configuration object when the script or css method was called. Default: null.
nodes (array) An array containing references to node(s) created in processing the transaction. These will be script nodes for JavaScript and link nodes for CSS.
win (obj) The window object in which the nodes were created.
purge() (function) Calling the returned purge() method will immediately remove the created nodes. This is safe and prudent for JavaScript nodes, which do not need to persist. If CSS nodes are purged, the rules they contain are no longer available and the page will repaint accordingly.

All of these fields are accessible on the object passed to your onSuccess callback:

  1. var successHandler = function(o) {
  2. //Here, o contains all of the fields described in the table
  3. //above:
  4. o.purge(); //removes the script node immediately after executing;
  5. Y.log(o.data); //the data you passed in your configuration
  6. //object
  7.  
  8. }
  9.  
  10. var objTransaction = Y.Get.script("http://json.org/json.js", {
  11. onSuccess: successHandler,
  12. data: {
  13. field1: value1,
  14. field2: value2
  15. }
  16. });
  17.  
var successHandler = function(o) {
    //Here, o contains all of the fields described in the table
    //above:
    o.purge(); //removes the script node immediately after executing;
    Y.log(o.data); //the data you passed in your configuration
                    //object
 
}
 
var objTransaction = Y.Get.script("http://json.org/json.js", {
    onSuccess: successHandler,
    data: {
        field1: value1,
        field2: value2
    }
});
 

Using the Get Utility to Insert Script Nodes

When you use the Y.Get.script() method to add one or more script nodes to the page, the Get Utility implements the following steps:

  1. A script node is appended to the target window for the first script file requested;
  2. the src attribute of the new script node is set to the specified URL;
  3. the script, in a successful transaction, is loaded and executed;
  4. the script node's load event fires;
  5. the Get Utility checks to see if more URLs remain to be loaded; if so, it recurses to step 1;
  6. if this was the last of the URLs specified for this transaction, the Get Utility invokes the onSuccess callback (if one has been specified);

The following is the general code pattern used to get scripts:

  1. var handlerData = {
  2. //data you wish to pass to your success or failure
  3. //handlers.
  4. };
  5.  
  6. var successHandler = function(oData) {
  7. //code to execute when all requested scripts have been
  8. //loaded; this code can make use of the contents of those
  9. //scripts, whether it's functional code or JSON data.
  10. };
  11.  
  12. var aURLs = [
  13. "/url1.js",
  14. "/url2.js",
  15. "/url3.js" //and so on
  16. ];
  17.  
  18. Y.Get.script(aURLs, {
  19. onSuccess: successHandler,
  20. data: handlerData
  21. });
  22.  
var handlerData = {
    //data you wish to pass to your success or failure
    //handlers.
};
 
var successHandler = function(oData) {
    //code to execute when all requested scripts have been
    //loaded; this code can make use of the contents of those
    //scripts, whether it's functional code or JSON data.
};
 
var aURLs = [
    "/url1.js",
    "/url2.js",
    "/url3.js" //and so on
];
 
Y.Get.script(aURLs, {
    onSuccess: successHandler,
    data: handlerData
});
 

Using the Get Utility to Insert CSS Files

When you use the Y.Get.css() method to add one or more CSS files to the page, the Get Utility follows the same steps described above for scripts. Generally speaking, the same code pattern holds as well. Note that Firefox and Safari at present do not support the load event on link nodes, so it is possible for CSS requests to load out of order in that browser. This can result in a different progressive display of styled in these browsers versus other browsers during CSS loading.

Support & Community

Forums & Blog

YUI 3 discussion forums are hosted on YUILibrary.com.

In addition, please visit the YUIBlog for updates and articles about the YUI Library written by the library's developers.

Filing Bugs & Feature Requests

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.

Copyright © 2010 Yahoo! Inc. All rights reserved. Copyright | Privacy Policy | Terms of Use | Job Openings