6
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Maven+Pro:400,700">
7
<link rel="stylesheet" href="../../build/cssgrids/grids-min.css">
8
<link rel="stylesheet" href="../assets/css/main.css">
9
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
10
<script src="../../build/yui/yui-min.js"></script>
18
<a href="#toc" class="jump">Jump to Table of Contents</a>
22
<div class="yui3-u-3-4">
24
<div class="content"><div class="intro">
26
The Get Utility makes it easy to dynamically load JavaScript and CSS resources and be notified when they've finished loading. Get is used internally by the <a href="../yui/index.html">YUI Loader</a> to load YUI modules and by the <a href="../jsonp/index.html">JSONP module</a> to make JSONP requests. The Get Utility is transactional in nature and is capable of loading multiple resources either serially or in parallel.
30
<h2 id="getting-started">Getting Started</h2>
33
To include the source files for Get and its dependencies, first load
34
the YUI seed file if you haven't already loaded it.
37
<pre class="code prettyprint"><script src="http://yui.yahooapis.com/3.5.0/build/yui/yui-min.js"></script></pre>
41
Next, create a new YUI instance for your application and populate it with the
42
modules you need by specifying them as arguments to the <code>YUI().use()</code> method.
43
YUI will automatically load any dependencies required by the modules you
47
<pre class="code prettyprint"><script>
48
// Create a new YUI instance and populate it with the required modules.
49
YUI().use('get', function (Y) {
50
// Get is available and ready for use. Add implementation
51
// code here.
53
</script></pre>
57
For more information on creating YUI instances and on the
58
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the
59
documentation for the <a href="../yui/index.html">YUI Global Object</a>.
63
<h2 id="using-the-get-utility">Using the Get Utility</h2>
65
<h3 id="loading-css-and-javascript">Loading CSS and JavaScript</h3>
67
<h4 id="js"><code>js()</code></h4>
70
To load a JavaScript resource, pass a URL (both relative and absolute URLs are fine) and a callback function to the <a href="http://yuilibrary.com/yui/docs/api/classes/Get.html#method_js"><code>Y.Get.js()</code></a> method. Get will execute the callback function when the resource has finished loading. If an error occurs, the first argument passed to the callback will be an array of error objects.
74
<code>Y.Get</code> is a static class, so you don't need to instantiate it before calling its methods.
77
<pre class="code prettyprint">// Load a single JavaScript resource.
78
Y.Get.js('http://example.com/file.js', function (err) {
80
Y.log('Error loading JS: ' + err[0].error, 'error');
84
Y.log('file.js loaded successfully!');
88
<h4 id="css"><code>css()</code></h4>
91
Loading CSS works the same way as JS, but you call the <a href="http://yuilibrary.com/yui/docs/api/classes/Get.html#method_css"><code>css()</code></a> method instead of <code>js()</code>:
94
<pre class="code prettyprint">// Load a single CSS resource.
95
Y.Get.css('file.css', function (err) {
97
Y.log('Error loading CSS: ' + err[0].error, 'error');
101
Y.log('file.css loaded successfully!');
105
<h4 id="load"><code>load()</code></h4>
108
If you want to load more than one resource in a single transaction and be notified when all of them have finished loading, you may pass an array of URLs to <code>css()</code> or <code>js()</code>.
111
<pre class="code prettyprint">// Load multiple JS resources and execute the callback after all have finished
112
// loading.
113
Y.Get.js(['one.js', 'two.js', 'http://example.com/three.js'], function (err) {
115
Y.Array.each(err, function (error) {
116
Y.log('Error loading JS: ' + error.error, 'error');
121
Y.log('All JS files loaded successfully!');
126
You can even mix and match both JavaScript and CSS files in the same transaction by calling <a href="http://yuilibrary.com/yui/docs/api/classes/Get.html#method_load"><code>Y.Get.load()</code></a>, which will guess the type of each URL by looking at the file extension.
129
<pre class="code prettyprint">// Load both CSS and JS in a single transaction and execute the callback after
130
// all resources have finished loading.
131
Y.Get.load(['widget.js', 'widget.css'], function (err) {
133
Y.Array.each(err, function (error) {
134
Y.log('Error loading file: ' + error.error, 'error');
139
Y.log('All CSS and JS files loaded successfully!');
144
This should be enough to get you started using the Get Utility, but keep reading to learn about Get's more advanced functionality.
147
<h3 id="serial-vs-parallel-loading">Serial vs. Parallel Loading</h3>
150
The <code>css()</code>, <code>js()</code>, and <code>load()</code> methods execute <em>asynchronously</em>, which means that they return instantly rather than blocking subsequent code until the operation finishes. This is why it's necessary to provide a callback function if you want to be notified when loading is complete.
154
It's also important to understand when resources will be loaded <em>serially</em> (one after another) versus in <em>parallel</em> (all at the same time). Loading resources in parallel is always faster than loading them serially, but can sometimes be dangerous because resources won't always finish loading in the same order they were requested.
158
The Get Utility always does the safest thing by default:
164
Transactions are processed serially. This means that only one transaction is in progress at a time, and it must finish before the next transaction will begin. Each call to <code>css()</code>, <code>js()</code>, or <code>load()</code> creates a transaction, although a single transaction may involve multiple requests.
170
Within a transaction, CSS resources are always loaded in parallel. This is because, with CSS, load order has no effect on the end result, since style precedence is determined by the order of <code><link></code> nodes in the DOM.
176
Within a transaction, JS resources are loaded in parallel in Firefox and Opera, because these browsers are capable of preserving script execution order regardless of load order. In all other browsers, JS resources are loaded serially unless the <a href="http://yuilibrary.com/yui/docs/api/classes/Get.html#property_options"><code>async</code> option</a> is set to <code>true</code>.
182
When the <a href="http://yuilibrary.com/yui/docs/api/classes/Get.html#property_options"><code>async</code> option</a> is set to <code>true</code>, JS resources are loaded in parallel regardless of the browser, and execution order is not guaranteed.
188
<h3 id="working-with-transactions">Working With Transactions</h3>
191
A transaction object is an instance of the <a href="http://yuilibrary.com/yui/docs/api/classes/Get.Transaction.html"><code>Y.Get.Transaction</code></a> class. It contains methods and properties that allow you to inspect and manipulate a transaction, which encompasses one or more CSS or JS requests and a set of config options associated with those requests.
195
The <code>css()</code>, <code>js()</code>, and <code>load()</code> methods each return a transaction object. This same transaction object is also passed as the second argument to the completion callback.
198
<pre class="code prettyprint">// Load a script and assign the transaction object to a var.
199
var tx = Y.Get.js('hello.js', function (err, tx) {
200
// The transaction object is also passed as the second arg to completion
201
// callbacks.
206
It's not necessary to hold onto a transaction object unless you want to be able to abort a request before it finishes or manually purge <code><script></code> or <code><link></code> nodes created by the transaction.
209
<h4 id="aborting-transactions">Aborting Transactions</h4>
212
You can abort a transaction in progress by calling the transaction's <a href="http://yuilibrary.com/yui/docs/api/classes/Get.Transaction.html#method_abort"><code>abort()</code></a> method.
215
<pre class="code prettyprint">var tx = Y.Get.js(['one.js', 'two.js'], function (err) {
217
Y.log(err[0].error, 'error');
221
tx.abort(); // Results in the log message "Aborted."</pre>
225
Pass a string to the <code>abort()</code> method to customize the error message passed to callbacks.
229
Note that since browsers don't expose a safe API for aborting in-progress JS and CSS requests, the Get Utility can't actually stop requests that have already started. Calling <code>abort()</code> will immediately cause callbacks to execute and will cancel any pending requests within the transaction that haven't yet begun, but if there are any requests already in progress, the browser will finish them silently.
232
<h4 id="purging-inserted-nodes">Purging Inserted Nodes</h4>
235
If you plan to load lots of JavaScript resources—for example, maybe your app makes frequent JSONP requests to a remote API—you'll end up creating lots of <code><script></code> nodes behind the scenes. Each node on the page uses a small amount of memory, and since the actual script nodes aren't usually needed once the JS has been executed, it's a good idea to clean them up occasionally by purging them.
239
By default, the Get Utility will automatically purge script nodes after every 20 requests. This number is relatively high since purging incurs a slight processing cost. If you want to manually purge the nodes inserted by a transaction instead of waiting for the automatic purge, you can do so by calling the transaction's <code>purge()</code> method.
242
<pre class="code prettyprint">Y.Get.js(['one.js', 'two.js'], function (err, tx) {
243
// Purge all the DOM nodes created by this transaction.
249
You can customize the automatic purge threshold by setting the <a href="http://yuilibrary.com/yui/docs/api/classes/Get.html#property_options"><code>purgethreshold</code></a> config option, and you can disable automatic purging completely by setting the <a href="http://yuilibrary.com/yui/docs/api/classes/Get.html#property_options"><code>autopurge</code></a> option to <code>false</code>.
253
Note that the Get Utility will not automatically purge CSS <code><link></code> nodes by default, since removing a <code><link></code> node from the DOM also removes any styles it applied. Calling <code>purge()</code> manually on a transaction that included CSS requests will purge the <code><link></code> nodes and remove styles, so be careful.
256
<h4 id="manually-executing-transactions">Manually Executing Transactions</h4>
259
As described in <a href="#serial-vs-parallel-loading">Serial vs. Parallel Loading</a>, the Get Utility executes transactions serially (one after the other) to ensure that they don't conflict with one another. If for some reason you want multiple transactions to execute in parallel and you're willing to take your life into your own hands, you can manually start a transaction by calling its <code>execute()</code> method.
262
<pre class="code prettyprint">var txOne = Y.Get.js(['foo.js', 'bar.js']),
263
txTwo = Y.Get.js(['baz.js', 'quux.js']);
265
// txOne is started automatically, and we can manually start txTwo in parallel.
266
txTwo.execute();</pre>
270
Calling <code>execute()</code> on a transaction that's already in progress or has already finished is safe and won't restart the transaction.
274
An additional feature of <code>execute()</code> is that it accepts a callback function, which works just like the callback function passed to <code>css()</code>, <code>js()</code>, or <code>load()</code>. In fact, you can even call <code>execute()</code> multiple times to register multiple callback functions, and they'll be queued and executed in order once the transaction finishes. If you call <code>execute()</code> with a callback function on a transaction that's already finished, the callback will be executed immediately.
277
<h3 id="configuration-options">Configuration Options</h3>
280
The Get Utility supports the following config options. All options may be set at the transaction level. Some options may also be set at the request level (i.e., for a specific URL within a transaction). Options that may be set at the request level are indicated by a "Y" in the "Request?" column.
295
<td><code>async</code></td>
296
<td><code>false</code></td>
297
<td style="text-align:center">Y</td>
299
Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously.
304
<td><code>attributes</code></td>
313
<td style="text-align:center">Y</td>
315
HTML attribute name/value pairs that should be added to inserted nodes. By default, the <code>charset</code> attribute will be set to "utf-8" and nodes will be given an auto-generated <code>id</code> attribute, but you can override these with your own values if desired.
320
<td><code>autopurge</code></td>
322
<code>true</code> for JS<br>
323
<code>false</code> for CSS
327
Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is <code>true</code> by default for JavaScript, but <code>false</code> for CSS since purging a CSS node will also remove any styling applied by the referenced file.
332
<td><code>context</code></td>
333
<td><em>transaction object</em></td>
336
<code>this</code> object to use when calling callback functions. Defaults to the transaction object.
341
<td><code>data</code></td>
342
<td><code>undefined</code></td>
345
Arbitrary data object to pass to "on*" callbacks.
350
<td><code>doc</code></td>
351
<td><code>Y.config.doc</code></td>
352
<td style="text-align:center">Y</td>
354
Document into which nodes should be inserted. By default, the current document is used.
359
<td><code>insertBefore</code></td>
360
<td><em>auto</em></td>
361
<td style="text-align:center">Y</td>
363
HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility.
368
<td><code>onEnd</code></td>
369
<td><code>undefined</code></td>
372
Callback to execute after a transaction is complete, regardless of whether it succeeded or failed.
377
<td><code>onFailure</code></td>
378
<td><code>undefined</code></td>
381
Callback to execute after a transaction fails, times out, or is aborted.
386
<td><code>onProgress</code></td>
387
<td><code>undefined</code></td>
390
Callback to execute after each individual request in a transaction either succeeds or fails.
395
<td><code>onSuccess</code></td>
396
<td><code>undefined</code></td>
399
Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the <code>error</code> event on CSS <code><link></code> nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources.
404
<td><code>onTimeout</code></td>
405
<td><code>undefined</code></td>
408
Callback to execute after a transaction times out.
413
<td><code>pollInterval</code></td>
414
<td><code>50</code></td>
417
Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the <code>load</code> event on <code><link></code> nodes. This isn't used for JavaScript.
422
<td><code>purgethreshold</code></td>
423
<td><code>20</code></td>
426
Number of nodes to insert before triggering an automatic purge when <code>autopurge</code> is <code>true</code>.
431
<td><code>timeout</code></td>
432
<td><code>undefined</code></td>
435
Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the <code>onTimeout</code> callback is called, followed by <code>onFailure</code> and finally <code>onEnd</code>. By default, there is no timeout.
440
<td><code>type</code></td>
441
<td><em>auto</em></td>
442
<td style="text-align:center">Y</td>
444
Resource type ("css" or "js"). This option is set automatically by the <code>css()</code> and <code>js()</code> functions and will be ignored there, but may be useful when using the <code>load()</code> function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension.
450
<h4 id="using-transaction-specific-options">Using Transaction-Specific Options</h4>
453
Transaction-specific configuration options apply only to a single transaction. To specify one or more transaction-specific options, just pass a config object as the second argument to <code>css()</code>, <code>js()</code> or <code>load()</code>.
456
<pre class="code prettyprint">Y.Get.js('intl-jp.js', {
458
'charset': 'shift-jis', // custom charset attribute for inserted DOM nodes
459
'class' : 'intl' // custom 'class' attribute for inserted DOM nodes
462
timeout: 10000 // timeout after 10 seconds
469
You may have noticed that in the example above, the options object is the second argument and the callback is the third argument, whereas previous examples pass a callback as the second argument and no options object. The <code>css()</code>, <code>js()</code>, and <code>load()</code> methods support both signatures for convenience. The only required argument is the first one.
472
<h4 id="using-request-specific-options">Using Request-Specific Options</h4>
475
Certain config options (see <a href="#configuration-options">the table above</a> for a complete list) can be specified on a per-request basis, meaning they'll apply only to a single URL.
479
To specify request-specific options, pass an object or array of objects to <code>css()</code>, <code>js()</code>, or <code>load()</code> instead of passing a string or array of strings. Each object must have a <code>url</code> property specifying the URL to load, and may also contain request-specific options. You can freely mix and match string URLs and objects if desired.
482
<pre class="code prettyprint">Y.Get.js([
483
{url: 'thing-one.js', attributes: {id: 'thing-one'}},
484
{url: 'thing-two.js', attributes: {id: 'thing-two'}, async: true}
491
When both request-specific options and transaction-specific options are specified, the options will be merged per request, with request-specific options taking precedence when there are collisions.
494
<h3 id="granular-callbacks">Granular Callbacks</h3>
497
While the callback parameter of the <code>css()</code>, <code>js()</code>, and <code>load()</code> methods makes it easy to define a combined success/failure callback for a transaction, there are times when more granularity is needed. Perhaps you want to use separate callbacks for success and failure, or perhaps you want to be notified of the progress of each request in a transaction rather than waiting until the entire transaction is complete. That's where granular callbacks come in.
501
The Get Utility supports five different granular callbacks per transaction: <code>onEnd</code>, <code>onFailure</code>, <code>onProgress</code>, <code>onSuccess</code>, and <code>onTimeout</code>. See <a href="#configuration-options">Configuration Options</a> for descriptions of when each callback is called.
505
Granular callbacks receive the transaction object as an argument.
508
<pre class="code prettyprint">Y.Get.js('kittens.js', {
509
onFailure: function () {
510
Y.log('Failure!');
513
onSuccess: function () {
514
Y.log('Success!');
520
You can pass arbitrary data to your callbacks by setting the <code>data</code> option on the transaction.
523
<pre class="code prettyprint">Y.Get.js(['one.js', 'two.js', 'three.js'], {
526
onProgress: function (tx) {
527
tx.data.progress += 1;
528
Y.log('Loaded ' + tx.data.progress + ' file(s)');
534
By default, the <code>this</code> object inside a granular callback refers to the transaction object, but you can customize it by setting the <code>context</code> option.
537
<pre class="code prettyprint">Y.Get.js('puppies.js', {
538
context: {bark: 'ruff ruff!'},
540
onSuccess: function () {
546
<h2 id="using-jsonp-apis">Using JSONP APIs</h2>
549
A common way to consume a web service that returns JSON data is to use a convention called <a href="http://en.wikipedia.org/wiki/JSONP">JSONP</a>. The remote service returns data wrapped in a JavaScript function call (the name of which is supplied in the request), so retrieving the data is simple as loading and executing the JSONP URL as if it were a script. When the returned JS executes, the data is passed to the named function.
553
The Get Utility can be used to consume JSONP APIs by loading JSONP URLs as scripts. However, the <a href="../jsonp/index.html">JSONP Utility</a> (which uses Get under the hood) provides a simplified API for making JSONP requests, so we recommend using that component for JSONP rather than using Get directly.
556
<h2 id="how-is-the-get-utility-different-from-io">How is the Get Utility Different From IO?</h2>
559
In simple terms, the Get Utility loads new JS or CSS resources into a document by creating new DOM nodes and setting the <code>src</code> or <code>href</code> attribute. Files loaded in this manner are processed (and, in the case of scripts, executed) as soon as they load.
562
<p>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. This makes the Get Utility ideal for loading scripts or CSS progressively (lazy loading) or for retrieving cross-domain JSON data from trusted sources, but somewhat less ideal for more sophisticated communication.
566
The basic version of the <a href="../io/index.html">IO Utility</a> (<code>io-base</code>) uses the <code>XMLHttpRequest</code> object to interact with the server. <code>XMLHttpRequest</code> is limited by a strict <a href="http://en.wikipedia.org/wiki/Same_origin_policy">same origin policy</a>, 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.
570
The IO Utility also supports cross domain requests through the <code>io-xdr</code> module. However, there are specific trust requirements as described in the documentation for the <a href="../io/index.html#xdr">IO Utility</a>. The <code>io-xdr</code> 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.
576
<div class="yui3-u-1-4">
577
<div class="sidebar">
579
<div id="toc" class="sidebox">
581
<h2 class="no-toc">Table of Contents</h2>
587
<a href="#getting-started">Getting Started</a>
590
<a href="#using-the-get-utility">Using the Get Utility</a>
593
<a href="#loading-css-and-javascript">Loading CSS and JavaScript</a>
596
<a href="#js"><code>js()</code></a>
599
<a href="#css"><code>css()</code></a>
602
<a href="#load"><code>load()</code></a>
607
<a href="#serial-vs-parallel-loading">Serial vs. Parallel Loading</a>
610
<a href="#working-with-transactions">Working With Transactions</a>
613
<a href="#aborting-transactions">Aborting Transactions</a>
616
<a href="#purging-inserted-nodes">Purging Inserted Nodes</a>
619
<a href="#manually-executing-transactions">Manually Executing Transactions</a>
624
<a href="#configuration-options">Configuration Options</a>
627
<a href="#using-transaction-specific-options">Using Transaction-Specific Options</a>
630
<a href="#using-request-specific-options">Using Request-Specific Options</a>
635
<a href="#granular-callbacks">Granular Callbacks</a>
640
<a href="#using-jsonp-apis">Using JSONP APIs</a>
643
<a href="#how-is-the-get-utility-different-from-io">How is the Get Utility Different From IO?</a>
658
<script src="../assets/vendor/prettify/prettify-min.js"></script>
659
<script>prettyPrint();</script>