2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
8 YUI.add('get', function(Y) {
13 * Provides a mechanism to fetch remote resources and
14 * insert them into a document.
22 TYPE_JS = "text/javascript",
23 TYPE_CSS = "text/css",
24 STYLESHEET = "stylesheet";
27 * Fetches and inserts one or more script or link nodes into the document
34 * hash of queues to manage multiple requests
41 * queue index used to generate transaction ids
49 * interal property used to prevent multiple simultaneous purge
59 * Generates an HTML element, this is not appended to a document
61 * @param type {string} the type of element
62 * @param attr {string} the attributes
63 * @param win {Window} optional window to create the element in
64 * @return {HTMLElement} the generated node
67 _node = function(type, attr, win) {
68 var w = win || Y.config.win, d=w.document, n=d.createElement(type),
72 if (attr[i] && attr.hasOwnProperty(i)) {
73 n.setAttribute(i, attr[i]);
81 * Generates a link node
83 * @param url {string} the url for the css file
84 * @param win {Window} optional window to create the node in
85 * @param attributes optional attributes collection to apply to the new node
86 * @return {HTMLElement} the generated node
89 _linkNode = function(url, win, attributes) {
99 return _node("link", o, win);
103 * Generates a script node
104 * @method _scriptNode
105 * @param url {string} the url for the script file
106 * @param win {Window} optional window to create the node in
107 * @param attributes optional attributes collection to apply to the new node
108 * @return {HTMLElement} the generated node
111 _scriptNode = function(url, win, attributes) {
119 Y.mix(o, attributes);
122 return _node("script", o, win);
126 * Removes the nodes for the specified queue
130 _purge = function(tId) {
131 var q=queues[tId], n, l, d, h, s, i, node, attr;
136 h = d.getElementsByTagName("head")[0];
138 if (q.insertBefore) {
139 s = _get(q.insertBefore, tId);
145 for (i=0; i<l; i=i+1) {
147 if (node.clearAttributes) {
148 node.clearAttributes();
150 // This is a hostile delete
151 // operation attempting to improve
152 // memory performance. As such, the
153 // hasOwnProperty check is intentionally
167 * Returns the data payload for callback functions
168 * @method _returnData
171 _returnData = function(q, msg, result) {
186 * The transaction is finished
188 * @param id {string} the id of the request
191 _end = function(id, msg, result) {
192 var q = queues[id], sc;
195 q.onEnd.call(sc, _returnData(q, msg, result));
200 * The request failed, execute fail handler with whatever
201 * was accomplished. There isn't a failure case at the
202 * moment unless you count aborted transactions
204 * @param id {string} the id of the request
207 _fail = function(id, msg) {
210 var q = queues[id], sc;
213 clearTimeout(q.timer);
216 // execute failure callback
219 q.onFailure.call(sc, _returnData(q, msg));
222 _end(id, msg, 'failure');
225 _get = function(nId, tId) {
227 n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId;
229 _fail(tId, "target node not found: " + nId);
236 * The request is complete, so executing the requester's callback
238 * @param id {string} the id of the request
241 _finish = function(id) {
242 var q = queues[id], msg, sc;
245 clearTimeout(q.timer);
250 msg = "transaction " + id + " was aborted";
255 // execute success callback
258 q.onSuccess.call(sc, _returnData(q));
267 * @param id {string} the id of the request
270 _timeout = function(id) {
271 var q = queues[id], sc;
274 q.onTimeout.call(sc, _returnData(q));
277 _end(id, 'timeout', 'timeout');
282 * Loads the next item for a given request
284 * @param id {string} the id of the request
285 * @param loaded {string} the url that was just loaded, if any
288 _next = function(id, loaded) {
291 var q = queues[id], msg, w, d, h, n, url, s;
295 clearTimeout(q.timer);
299 msg = "transaction " + id + " was aborted";
310 // This is the first pass: make sure the url is an array
311 q.url = (L.isString(q.url)) ? [q.url] : q.url;
313 q.varName = (L.isString(q.varName)) ? [q.varName] : q.varName;
319 h = d.getElementsByTagName("head")[0];
321 if (q.url.length === 0) {
328 // if the url is undefined, this is probably a trailing comma problem in IE
336 // q.timer = L.later(q.timeout, q, _timeout, id);
337 q.timer = setTimeout(function() {
342 if (q.type === "script") {
343 n = _scriptNode(url, w, q.attributes);
345 n = _linkNode(url, w, q.attributes);
348 // track this node's load progress
349 _track(q.type, n, id, url, w, q.url.length);
351 // add the node to the queue so we can return it to the user supplied callback
354 // add it to the head or insert it before 'insertBefore'
355 if (q.insertBefore) {
356 s = _get(q.insertBefore, id);
358 s.parentNode.insertBefore(n, s);
365 // FireFox does not support the onload event for link nodes, so there is
366 // no way to make the css requests synchronous. This means that the css
367 // rules in multiple files could be applied out of order in this browser
368 // if a later request returns before an earlier one. Safari too.
369 if ((ua.webkit || ua.gecko) && q.type === "css") {
375 * Removes processed queues and corresponding nodes
379 _autoPurge = function() {
390 if (queues.hasOwnProperty(i)) {
392 if (q.autopurge && q.finished) {
403 * Saves the state for the request and begins loading
406 * @param type {string} the type of node to insert
407 * @param url {string} the url to load
408 * @param opts the hash of options for this request
411 _queue = function(type, url, opts) {
415 var id = "q" + (qidx++), q,
416 thresh = opts.purgethreshold || Y.Get.PURGE_THRESH;
418 if (qidx % thresh === 0) {
422 queues[id] = Y.merge(opts, {
431 q.win = q.win || Y.config.win;
432 q.context = q.context || q;
433 q.autopurge = ("autopurge" in q) ? q.autopurge :
434 (type === "script") ? true : false;
437 q.attributes = q.attributes || {};
438 q.attributes.charset = opts.charset;
441 // L.later(0, q, _next, id);
442 setTimeout(function() {
452 * Detects when a node has been loaded. In the case of
453 * script nodes, this does not guarantee that contained
454 * script is ready to use.
456 * @param type {string} the type of node to track
457 * @param n {HTMLElement} the node to track
458 * @param id {string} the id of the request
459 * @param url {string} the url that is being loaded
460 * @param win {Window} the targeted window
461 * @param qlength the number of remaining items in the queue,
463 * @param trackfn {Function} function to execute when finished
464 * the default is _next
467 _track = function(type, n, id, url, win, qlength, trackfn) {
468 var f = trackfn || _next;
470 // IE supports the readystatechange event for script and css nodes
471 // Opera only for script nodes. Opera support onload for script
472 // nodes, but this doesn't fire when there is a load failure.
473 // The onreadystatechange appears to be a better way to respond
474 // to both success and failure.
476 n.onreadystatechange = function() {
477 var rs = this.readyState;
478 if ("loaded" === rs || "complete" === rs) {
479 n.onreadystatechange = null;
484 // webkit prior to 3.x is no longer supported
485 } else if (ua.webkit) {
487 if (type === "script") {
488 // Safari 3.x supports the load event for script nodes (DOM2)
489 n.addEventListener("load", function() {
494 // FireFox and Opera support onload (but not DOM2 in FF) handlers for
495 // script nodes. Opera, but not FF, supports the onload event for link
499 n.onload = function() {
503 n.onerror = function(e) {
504 _fail(id, e + ": " + url);
512 * The number of request required before an automatic purge.
513 * Can be configured via the 'purgethreshold' config
514 * property PURGE_THRESH
523 * Called by the the helper for detecting script load in Safari
526 * @param id {string} the transaction id
529 _finalize: function(id) {
530 // L.later(0, null, _finish, id);
531 setTimeout(function() {
537 * Abort a transaction
540 * @param o {string|object} Either the tId or the object returned from
544 var id = (L.isString(o)) ? o : o.tId,
552 * Fetches and inserts one or more script nodes into the head
553 * of the current document or the document in a specified window.
557 * @param url {string|string[]} the url or urls to the script(s)
558 * @param opts {object} Options:
562 * callback to execute when the script(s) are finished loading
563 * The callback receives an object back with the following
567 * <dd>the window the script(s) were inserted into</dd>
569 * <dd>the data object passed in when the request was made</dd>
571 * <dd>An array containing references to the nodes that were
574 * <dd>A function that, when executed, will remove the nodes
575 * that were inserted</dd>
581 * callback to execute when a timeout occurs.
582 * The callback receives an object back with the following
586 * <dd>the window the script(s) were inserted into</dd>
588 * <dd>the data object passed in when the request was made</dd>
590 * <dd>An array containing references to the nodes that were
593 * <dd>A function that, when executed, will remove the nodes
594 * that were inserted</dd>
599 * <dd>a function that executes when the transaction finishes, regardless of the exit path</dd>
602 * callback to execute when the script load operation fails
603 * The callback receives an object back with the following
607 * <dd>the window the script(s) were inserted into</dd>
609 * <dd>the data object passed in when the request was made</dd>
611 * <dd>An array containing references to the nodes that were
612 * inserted successfully</dd>
614 * <dd>A function that, when executed, will remove any nodes
615 * that were inserted</dd>
620 * <dd>the execution context for the callbacks</dd>
622 * <dd>a window other than the one the utility occupies</dd>
625 * setting to true will let the utilities cleanup routine purge
626 * the script once loaded
628 * <dt>purgethreshold</dt>
630 * The number of transaction before autopurge should be initiated
634 * data that is supplied to the callback when the script(s) are
637 * <dt>insertBefore</dt>
638 * <dd>node or node id that will become the new node's nextSibling</dd>
641 * <dd>Node charset, default utf-8 (deprecated, use the attributes config)</dd>
642 * <dt>attributes</dt>
643 * <dd>An object literal containing additional attributes to add to the link tags</dd>
645 * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd>
647 * Y.Get.script(
648 * ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js",
649 * "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], {
650 * onSuccess: function(o) {
651 * this.log("won't cause error because Y is the context");
652 * },
653 * onFailure: function(o) {
654 * },
655 * onTimeout: function(o) {
656 * },
657 * data: "foo",
658 * timeout: 10000, // 10 second timeout
659 * context: Y, // make the YUI instance
660 * // win: otherframe // target another window/frame
661 * autopurge: true // allow the utility to choose when to remove the nodes
662 * purgetheshold: 1 // purge previous transaction before next transaction
663 * });
665 * @return {tId: string} an object containing info about the transaction
667 script: function(url, opts) {
668 return _queue("script", url, opts);
672 * Fetches and inserts one or more css link nodes into the
673 * head of the current document or the document in a specified
677 * @param url {string} the url or urls to the css file(s)
678 * @param opts Options:
682 * callback to execute when the css file(s) are finished loading
683 * The callback receives an object back with the following
686 * <dd>the window the link nodes(s) were inserted into</dd>
688 * <dd>the data object passed in when the request was made</dd>
690 * <dd>An array containing references to the nodes that were
693 * <dd>A function that, when executed, will remove the nodes
694 * that were inserted</dd>
699 * <dd>the execution context for the callbacks</dd>
701 * <dd>a window other than the one the utility occupies</dd>
704 * data that is supplied to the callbacks when the nodes(s) are
707 * <dt>insertBefore</dt>
708 * <dd>node or node id that will become the new node's nextSibling</dd>
710 * <dd>Node charset, default utf-8 (deprecated, use the attributes config)</dd>
711 * <dt>attributes</dt>
712 * <dd>An object literal containing additional attributes to add to the link tags</dd>
715 * Y.Get.css("http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css");
718 * Y.Get.css(
719 * ["http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css",
720 * insertBefore: 'custom-styles' // nodes will be inserted before the specified node
721 * });
723 * @return {tId: string} an object containing info about the transaction
725 css: function(url, opts) {
726 return _queue("css", url, opts);