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 * Provides a mechanism to fetch remote resources and
9 * insert them into a document
15 * Fetches and inserts one or more script or link nodes into the document
16 * @namespace YAHOO.util
17 * @class YAHOO.util.Get
19 YAHOO.util.Get = function() {
22 * hash of queues to manage multiple requests
29 * queue index used to generate transaction ids
37 * node index used to generate unique node ids
49 * interal property used to prevent multiple simultaneous purge
62 * Generates an HTML element, this is not appended to a document
64 * @param type {string} the type of element
65 * @param attr {string} the attributes
66 * @param win {Window} optional window to create the element in
67 * @return {HTMLElement} the generated node
70 var _node = function(type, attr, win) {
71 var w = win || window, d=w.document, n=d.createElement(type);
74 if (attr[i] && YAHOO.lang.hasOwnProperty(attr, i)) {
75 n.setAttribute(i, attr[i]);
83 * Generates a link node
85 * @param url {string} the url for the css file
86 * @param win {Window} optional window to create the node in
87 * @return {HTMLElement} the generated node
90 var _linkNode = function(url, win, attributes) {
93 id: "yui__dyn_" + (nidx++),
100 lang.augmentObject(o, attributes);
103 return _node("link", o, win);
107 * Generates a script node
108 * @method _scriptNode
109 * @param url {string} the url for the script file
110 * @param win {Window} optional window to create the node in
111 * @return {HTMLElement} the generated node
114 var _scriptNode = function(url, win, attributes) {
116 id: "yui__dyn_" + (nidx++),
117 type: "text/javascript",
122 lang.augmentObject(o, attributes);
125 return _node("script", o, win);
129 * Returns the data payload for callback functions
130 * @method _returnData
133 var _returnData = function(q, msg) {
146 var _get = function(nId, tId) {
148 n = (lang.isString(nId)) ? q.win.document.getElementById(nId) : nId;
150 _fail(tId, "target node not found: " + nId);
157 * The request failed, execute fail handler with whatever
158 * was accomplished. There isn't a failure case at the
159 * moment unless you count aborted transactions
161 * @param id {string} the id of the request
164 var _fail = function(id, msg) {
166 // execute failure callback
168 var sc=q.scope || q.win;
169 q.onFailure.call(sc, _returnData(q, msg));
174 * The request is complete, so executing the requester's callback
176 * @param id {string} the id of the request
179 var _finish = function(id) {
184 var msg = "transaction " + id + " was aborted";
189 // execute success callback
191 var sc=q.scope || q.win;
192 q.onSuccess.call(sc, _returnData(q));
199 * @param id {string} the id of the request
202 var _timeout = function(id) {
206 q.onTimeout.call(sc, _returnData(q));
211 * Loads the next item for a given request
213 * @param id {string} the id of the request
214 * @param loaded {string} the url that was just loaded, if any
217 var _next = function(id, loaded) {
221 // Y.log('cancel timer');
226 var msg = "transaction " + id + " was aborted";
237 // This is the first pass: make sure the url is an array
238 q.url = (lang.isString(q.url)) ? [q.url] : q.url;
240 q.varName = (lang.isString(q.varName)) ? [q.varName] : q.varName;
244 var w=q.win, d=w.document, h=d.getElementsByTagName("head")[0], n;
246 if (q.url.length === 0) {
247 // Safari 2.x workaround - There is no way to know when
248 // a script is ready in versions of Safari prior to 3.x.
249 // Adding an extra node reduces the problem, but doesn't
250 // eliminate it completely because the browser executes
251 // them asynchronously.
252 if (q.type === "script" && ua.webkit && ua.webkit < 420 &&
253 !q.finalpass && !q.varName) {
254 // Add another script node. This does not guarantee that the
255 // scripts will execute in order, but it does appear to fix the
256 // problem on fast connections more effectively than using an
257 // arbitrary timeout. It is possible that the browser does
258 // block subsequent script execution in this case for a limited
260 var extra = _scriptNode(null, q.win, q.attributes);
261 extra.innerHTML='YAHOO.util.Get._finalize("' + id + '");';
262 q.nodes.push(extra); h.appendChild(extra);
274 // if the url is undefined, this is probably a trailing comma problem in IE
282 // Y.log('create timer');
283 q.timer = lang.later(q.timeout, q, _timeout, id);
286 if (q.type === "script") {
287 n = _scriptNode(url, w, q.attributes);
289 n = _linkNode(url, w, q.attributes);
292 // track this node's load progress
293 _track(q.type, n, id, url, w, q.url.length);
295 // add the node to the queue so we can return it to the user supplied callback
298 // add it to the head or insert it before 'insertBefore'
299 if (q.insertBefore) {
300 var s = _get(q.insertBefore, id);
302 s.parentNode.insertBefore(n, s);
309 // FireFox does not support the onload event for link nodes, so there is
310 // no way to make the css requests synchronous. This means that the css
311 // rules in multiple files could be applied out of order in this browser
312 // if a later request returns before an earlier one. Safari too.
313 if ((ua.webkit || ua.gecko) && q.type === "css") {
319 * Removes processed queues and corresponding nodes
323 var _autoPurge = function() {
330 for (var i in queues) {
332 if (q.autopurge && q.finished) {
342 * Removes the nodes for the specified queue
346 var _purge = function(tId) {
353 h = d.getElementsByTagName("head")[0],
356 if (q.insertBefore) {
357 sib = _get(q.insertBefore, tId);
363 for (i=0; i<l; i=i+1) {
365 if (node.clearAttributes) {
366 node.clearAttributes();
381 * Saves the state for the request and begins loading
384 * @param type {string} the type of node to insert
385 * @param url {string} the url to load
386 * @param opts the hash of options for this request
389 var _queue = function(type, url, opts) {
391 var id = "q" + (qidx++);
394 if (qidx % YAHOO.util.Get.PURGE_THRESH === 0) {
398 queues[id] = lang.merge(opts, {
408 q.win = q.win || window;
409 q.scope = q.scope || q.win;
410 q.autopurge = ("autopurge" in q) ? q.autopurge :
411 (type === "script") ? true : false;
414 q.attributes = q.attributes || {};
415 q.attributes.charset = opts.charset;
418 lang.later(0, q, _next, id);
426 * Detects when a node has been loaded. In the case of
427 * script nodes, this does not guarantee that contained
428 * script is ready to use.
430 * @param type {string} the type of node to track
431 * @param n {HTMLElement} the node to track
432 * @param id {string} the id of the request
433 * @param url {string} the url that is being loaded
434 * @param win {Window} the targeted window
435 * @param qlength the number of remaining items in the queue,
437 * @param trackfn {Function} function to execute when finished
438 * the default is _next
441 var _track = function(type, n, id, url, win, qlength, trackfn) {
442 var f = trackfn || _next;
444 // IE supports the readystatechange event for script and css nodes
446 n.onreadystatechange = function() {
447 var rs = this.readyState;
448 if ("loaded" === rs || "complete" === rs) {
449 n.onreadystatechange = null;
454 // webkit prior to 3.x is problemmatic
455 } else if (ua.webkit) {
457 if (type === "script") {
459 // Safari 3.x supports the load event for script nodes (DOM2)
460 if (ua.webkit >= 420) {
462 n.addEventListener("load", function() {
466 // Nothing can be done with Safari < 3.x except to pause and hope
467 // for the best, particularly after last script is inserted. The
468 // scripts will always execute in the order they arrive, not
469 // necessarily the order in which they were inserted. To support
470 // script nodes with complete reliability in these browsers, script
471 // nodes either need to invoke a function in the window once they
472 // are loaded or the implementer needs to provide a well-known
473 // property that the utility can poll for.
475 // Poll for the existence of the named variable, if it
479 var freq=YAHOO.util.Get.POLL_FREQ;
480 q.maxattempts = YAHOO.util.Get.TIMEOUT/freq;
482 q._cache = q.varName[0].split(".");
483 q.timer = lang.later(freq, q, function(o) {
484 var a=this._cache, l=a.length, w=this.win, i;
485 for (i=0; i<l; i=i+1) {
488 // if we have exausted our attempts, give up
490 if (this.attempts++ > this.maxattempts) {
491 var msg = "Over retry limit, giving up";
506 lang.later(YAHOO.util.Get.POLL_FREQ, null, f, [id, url]);
511 // FireFox and Opera support onload (but not DOM2 in FF) handlers for
512 // script nodes. Opera, but not FF, supports the onload event for link
515 n.onload = function() {
524 * The default poll freqency in ms, when needed
525 * @property POLL_FREQ
533 * The number of request required before an automatic purge.
534 * property PURGE_THRESH
542 * The length time to poll for varName when loading a script in
543 * Safari 2.x before the transaction fails.
552 * Called by the the helper for detecting script load in Safari
554 * @param id {string} the transaction id
557 _finalize: function(id) {
558 lang.later(0, null, _finish, id);
562 * Abort a transaction
564 * @param {string|object} either the tId or the object returned from
568 var id = (lang.isString(o)) ? o : o.tId;
576 * Fetches and inserts one or more script nodes into the head
577 * of the current document or the document in a specified window.
581 * @param url {string|string[]} the url or urls to the script(s)
582 * @param opts {object} Options:
586 * callback to execute when the script(s) are finished loading
587 * The callback receives an object back with the following
591 * <dd>the window the script(s) were inserted into</dd>
593 * <dd>the data object passed in when the request was made</dd>
595 * <dd>An array containing references to the nodes that were
598 * <dd>A function that, when executed, will remove the nodes
599 * that were inserted</dd>
605 * callback to execute when the script load operation fails
606 * The callback receives an object back with the following
610 * <dd>the window the script(s) were inserted into</dd>
612 * <dd>the data object passed in when the request was made</dd>
614 * <dd>An array containing references to the nodes that were
615 * inserted successfully</dd>
617 * <dd>A function that, when executed, will remove any nodes
618 * that were inserted</dd>
624 * callback to execute when a timeout occurs.
625 * The callback receives an object back with the following
629 * <dd>the window the script(s) were inserted into</dd>
631 * <dd>the data object passed in when the request was made</dd>
633 * <dd>An array containing references to the nodes that were
636 * <dd>A function that, when executed, will remove the nodes
637 * that were inserted</dd>
642 * <dd>the execution context for the callbacks</dd>
644 * <dd>a window other than the one the utility occupies</dd>
647 * setting to true will let the utilities cleanup routine purge
648 * the script once loaded
652 * data that is supplied to the callback when the script(s) are
657 * variable that should be available when a script is finished
658 * loading. Used to help Safari 2.x and below with script load
659 * detection. The type of this property should match what was
660 * passed into the url parameter: if loading a single url, a
661 * string can be supplied. If loading multiple scripts, you
662 * must supply an array that contains the variable name for
665 * <dt>insertBefore</dt>
666 * <dd>node or node id that will become the new node's nextSibling</dd>
669 * <dd>Node charset, deprecated, use 'attributes'</dd>
670 * <dt>attributes</dt>
671 * <dd>A hash of attributes to apply to dynamic nodes.</dd>
673 * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd>
675 * // assumes yahoo, dom, and event are already on the page
676 * YAHOO.util.Get.script(
677 * ["http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js",
678 * "http://yui.yahooapis.com/2.7.0/build/animation/animation-min.js"], {
679 * onSuccess: function(o) {
680 * new YAHOO.util.DDProxy("dd1"); // also new o.reference("dd1"); would work
681 * this.log("won't cause error because YAHOO is the scope");
682 * this.log(o.nodes.length === 2) // true
683 * // o.purge(); // optionally remove the script nodes immediately
684 * },
685 * onFailure: function(o) {
686 * },
687 * data: "foo",
688 * timeout: 10000, // 10 second timeout
689 * scope: YAHOO,
690 * // win: otherframe // target another window/frame
691 * autopurge: true // allow the utility to choose when to remove the nodes
692 * });
694 * @return {tId: string} an object containing info about the transaction
696 script: function(url, opts) { return _queue("script", url, opts); },
699 * Fetches and inserts one or more css link nodes into the
700 * head of the current document or the document in a specified
704 * @param url {string} the url or urls to the css file(s)
705 * @param opts Options:
709 * callback to execute when the css file(s) are finished loading
710 * The callback receives an object back with the following
713 * <dd>the window the link nodes(s) were inserted into</dd>
715 * <dd>the data object passed in when the request was made</dd>
717 * <dd>An array containing references to the nodes that were
720 * <dd>A function that, when executed, will remove the nodes
721 * that were inserted</dd>
726 * <dd>the execution context for the callbacks</dd>
728 * <dd>a window other than the one the utility occupies</dd>
731 * data that is supplied to the callbacks when the nodes(s) are
734 * <dt>insertBefore</dt>
735 * <dd>node or node id that will become the new node's nextSibling</dd>
737 * <dd>Node charset, deprecated, use 'attributes'</dd>
738 * <dt>attributes</dt>
739 * <dd>A hash of attributes to apply to dynamic nodes.</dd>
742 * YAHOO.util.Get.css("http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css");
745 * YAHOO.util.Get.css(["http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css",
747 * @return {tId: string} an object containing info about the transaction
749 css: function(url, opts) {
750 return _queue("css", url, opts);
755 YAHOO.register("get", YAHOO.util.Get, {version: "2.8.0r4", build: "2449"});