Get

Jump to Table of Contents

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

Common use cases for the Get Utility include:

  • Cross-site data retrieval: Because XMLHttpRequest and the YUI IO Utility (which uses XMLHttpRequest) adhere to a strict same-origin policy, the retrieval of third-party data via XHR requires a server-side proxy.

    When 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.

    That said, it's crucial to understand that if there is malicious code present in the loaded script there is no safe way to protect 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..

  • 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.

    If you're loading YUI resources specifically, you may want to use the YUI Loader Utility. Loader employs the Get Utility under the hood to bring in YUI components and has an intrinsic understanding of the YUI dependency tree.

Getting Started

To include the source files for Get and its dependencies, first load the YUI seed file if you haven't already loaded it.

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

Next, create a new YUI instance for your application and populate it with the modules you need by specifying them as arguments to the YUI().use() method. YUI will automatically load any dependencies required by the modules you specify.

// Create a new YUI instance and populate it with the required modules.
YUI().use('get', function (Y) {
    // Get is available and ready for use. Add implementation
    // code here.
});

For more information on creating YUI instances and on the use() method, see the documentation for the YUI Global object.

Using the Get Utility

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

urls (String|String[])
A string or an array of strings designating the URL(s) you wish to load into the page.
options (Object)
An optional object containing configuration information for the transaction; see the Configuring a Transaction section below for the full list of configuraton options you can include here.

A sample request for a file might look like this:

Y.Get.script('http://example.com/file.js', {
  onSuccess: function () {
    Y.log('file loaded');
  }
});

If you want to hold onto a transaction object for the request, assign the return value to a variable:

var transaction = Y.Get.script('http://example.com/file.js', {
  onSuccess: function () {
    Y.log('file loaded');
  }
});

transaction will be an object with a single property, tId, which is a unique identifier of the transaction following the pattern "q0", "q1", "q2", etc.

It's only necessary to store the transaction object if you want to abort the request later.

Configuring a Transaction

The Get Utility is configured via the second argument to the script() or css() methods. This optional argument should be an object containing one or more of the following fields:

Name Type Description
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.
autopurge Boolean If 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.
context Object The this object to use when executing callbacks. Default: the current YUI instance.
data Any Data to pass as an argument to onSuccess or onFailure callbacks. Default: null.
onEnd Function Callback function invoked when a transaction completes, no matter how the transaction ended.
onFailure Function Callback function invoked when an error is detected or abort() is called.
onProgress Function Callback function invoked after each node is inserted.
onSuccess Function Callback function invoked when the requested file(s) have loaded successfully.
onTimeout Function Callback function invoked if a timeout is detected.
timeout Number Number of milliseconds to wait for a file to finish loading before timing out.
win Window The window into which the loaded resource(s) should be inserted. Default: Y.config.win.

Making Use of Arguments Supplied to Your Callback

As noted above, callback methods 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 a callback. Here's a summary of the fields contained in that argument object:

Property Type Description
data Any The data field you passed in the configuration object when the script() or css() method was called. Default: null.
nodes Array An array containing references to DOM node(s) created in processing the transaction. These will be script nodes for JavaScript and link nodes for CSS.
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.
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.
win Window The window object in which the nodes were created.

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

Y.Get.script('http://json.org/json.js', {
  onSuccess: function (e) {
    // e contains all of the fields described in the table above.

    e.purge(); // Removes the script node immediately after executing.
    Y.log(e.data); // Logs the data passed in the configuration object.
  },

  data: {
    foo: 'bar',
    baz: 'quux'
  }
});

Using JSONP APIs

A common way to consume a web service that returns JSON data is to use a convention called JSONP. The way it works is that the consumer of the web service supplies the name of a function to execute on the client. The web service response is expected to return a JavaScript response that executes this function and provides a JSON payload as a parameter to the function.

The JSONP component provides a simplified API for making JSONP requests using the Get Utility.

How is the Get Utility Different From IO?

The Get Utility inserts new script or CSS content into a window by creating new nodes and supplying a src or href attribute. Files inserted into the window in this manner are processed (and, in the case of scripts, executed) immediately upon load.

While query parameters can be passed in the URL, no data can be sent to the server via HTTP POST using this method; the Get Utility can only make HTTP GET requests.

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 basic version of the IO Utility (io-base) 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).

As a result, IO 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.

The IO Utility also supports cross domain requests through the io-xdr module. However, there are specific trust requirements as described in the documentation for the IO Utility. The io-xdr submodule may be a better choice than the Get Utility for cross-domain communication if the service you are accessing can be configured to trust the server that is hosting your application.

Known Issues

  • Gecko and WebKit-based browsers (Firefox, Chrome, and Safari) don't fire the DOM load event on a <link> node when a CSS file finishes loading. As a result, the Get Utility fires the onSuccess event immediately in these browsers. A workaround for this issue will be provided in a future release.