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) {
165 YAHOO.log("get failure: " + msg, "warn", "Get");
167 // execute failure callback
169 var sc=q.scope || q.win;
170 q.onFailure.call(sc, _returnData(q, msg));
175 * The request is complete, so executing the requester's callback
177 * @param id {string} the id of the request
180 var _finish = function(id) {
181 YAHOO.log("Finishing transaction " + id);
186 var msg = "transaction " + id + " was aborted";
191 // execute success callback
193 var sc=q.scope || q.win;
194 q.onSuccess.call(sc, _returnData(q));
201 * @param id {string} the id of the request
204 var _timeout = function(id) {
205 YAHOO.log("Timeout " + id, "info", "get");
209 q.onTimeout.call(sc, _returnData(q));
214 * Loads the next item for a given request
216 * @param id {string} the id of the request
217 * @param loaded {string} the url that was just loaded, if any
220 var _next = function(id, loaded) {
221 YAHOO.log("_next: " + id + ", loaded: " + loaded, "info", "Get");
225 // Y.log('cancel timer');
230 var msg = "transaction " + id + " was aborted";
241 // This is the first pass: make sure the url is an array
242 q.url = (lang.isString(q.url)) ? [q.url] : q.url;
244 q.varName = (lang.isString(q.varName)) ? [q.varName] : q.varName;
248 var w=q.win, d=w.document, h=d.getElementsByTagName("head")[0], n;
250 if (q.url.length === 0) {
251 // Safari 2.x workaround - There is no way to know when
252 // a script is ready in versions of Safari prior to 3.x.
253 // Adding an extra node reduces the problem, but doesn't
254 // eliminate it completely because the browser executes
255 // them asynchronously.
256 if (q.type === "script" && ua.webkit && ua.webkit < 420 &&
257 !q.finalpass && !q.varName) {
258 // Add another script node. This does not guarantee that the
259 // scripts will execute in order, but it does appear to fix the
260 // problem on fast connections more effectively than using an
261 // arbitrary timeout. It is possible that the browser does
262 // block subsequent script execution in this case for a limited
264 var extra = _scriptNode(null, q.win, q.attributes);
265 extra.innerHTML='YAHOO.util.Get._finalize("' + id + '");';
266 q.nodes.push(extra); h.appendChild(extra);
278 // if the url is undefined, this is probably a trailing comma problem in IE
281 YAHOO.log('skipping empty url');
285 YAHOO.log("attempting to load " + url, "info", "Get");
288 // Y.log('create timer');
289 q.timer = lang.later(q.timeout, q, _timeout, id);
292 if (q.type === "script") {
293 n = _scriptNode(url, w, q.attributes);
295 n = _linkNode(url, w, q.attributes);
298 // track this node's load progress
299 _track(q.type, n, id, url, w, q.url.length);
301 // add the node to the queue so we can return it to the user supplied callback
304 // add it to the head or insert it before 'insertBefore'
305 if (q.insertBefore) {
306 var s = _get(q.insertBefore, id);
308 s.parentNode.insertBefore(n, s);
314 YAHOO.log("Appending node: " + url, "info", "Get");
316 // FireFox does not support the onload event for link nodes, so there is
317 // no way to make the css requests synchronous. This means that the css
318 // rules in multiple files could be applied out of order in this browser
319 // if a later request returns before an earlier one. Safari too.
320 if ((ua.webkit || ua.gecko) && q.type === "css") {
326 * Removes processed queues and corresponding nodes
330 var _autoPurge = function() {
337 for (var i in queues) {
339 if (q.autopurge && q.finished) {
349 * Removes the nodes for the specified queue
353 var _purge = function(tId) {
360 h = d.getElementsByTagName("head")[0],
363 if (q.insertBefore) {
364 sib = _get(q.insertBefore, tId);
370 for (i=0; i<l; i=i+1) {
372 if (node.clearAttributes) {
373 node.clearAttributes();
388 * Saves the state for the request and begins loading
391 * @param type {string} the type of node to insert
392 * @param url {string} the url to load
393 * @param opts the hash of options for this request
396 var _queue = function(type, url, opts) {
398 var id = "q" + (qidx++);
401 if (qidx % YAHOO.util.Get.PURGE_THRESH === 0) {
405 queues[id] = lang.merge(opts, {
415 q.win = q.win || window;
416 q.scope = q.scope || q.win;
417 q.autopurge = ("autopurge" in q) ? q.autopurge :
418 (type === "script") ? true : false;
421 q.attributes = q.attributes || {};
422 q.attributes.charset = opts.charset;
425 lang.later(0, q, _next, id);
433 * Detects when a node has been loaded. In the case of
434 * script nodes, this does not guarantee that contained
435 * script is ready to use.
437 * @param type {string} the type of node to track
438 * @param n {HTMLElement} the node to track
439 * @param id {string} the id of the request
440 * @param url {string} the url that is being loaded
441 * @param win {Window} the targeted window
442 * @param qlength the number of remaining items in the queue,
444 * @param trackfn {Function} function to execute when finished
445 * the default is _next
448 var _track = function(type, n, id, url, win, qlength, trackfn) {
449 var f = trackfn || _next;
451 // IE supports the readystatechange event for script and css nodes
453 n.onreadystatechange = function() {
454 var rs = this.readyState;
455 if ("loaded" === rs || "complete" === rs) {
456 YAHOO.log(id + " onload " + url, "info", "Get");
457 n.onreadystatechange = null;
462 // webkit prior to 3.x is problemmatic
463 } else if (ua.webkit) {
465 if (type === "script") {
467 // Safari 3.x supports the load event for script nodes (DOM2)
468 if (ua.webkit >= 420) {
470 n.addEventListener("load", function() {
471 YAHOO.log(id + " DOM2 onload " + url, "info", "Get");
475 // Nothing can be done with Safari < 3.x except to pause and hope
476 // for the best, particularly after last script is inserted. The
477 // scripts will always execute in the order they arrive, not
478 // necessarily the order in which they were inserted. To support
479 // script nodes with complete reliability in these browsers, script
480 // nodes either need to invoke a function in the window once they
481 // are loaded or the implementer needs to provide a well-known
482 // property that the utility can poll for.
484 // Poll for the existence of the named variable, if it
488 var freq=YAHOO.util.Get.POLL_FREQ;
489 YAHOO.log("Polling for " + q.varName[0]);
490 q.maxattempts = YAHOO.util.Get.TIMEOUT/freq;
492 q._cache = q.varName[0].split(".");
493 q.timer = lang.later(freq, q, function(o) {
494 var a=this._cache, l=a.length, w=this.win, i;
495 for (i=0; i<l; i=i+1) {
498 // if we have exausted our attempts, give up
500 if (this.attempts++ > this.maxattempts) {
501 var msg = "Over retry limit, giving up";
505 YAHOO.log(a[i] + " failed, retrying");
511 YAHOO.log("Safari poll complete");
518 lang.later(YAHOO.util.Get.POLL_FREQ, null, f, [id, url]);
523 // FireFox and Opera support onload (but not DOM2 in FF) handlers for
524 // script nodes. Opera, but not FF, supports the onload event for link
527 n.onload = function() {
528 YAHOO.log(id + " onload " + url, "info", "Get");
537 * The default poll freqency in ms, when needed
538 * @property POLL_FREQ
546 * The number of request required before an automatic purge.
547 * property PURGE_THRESH
555 * The length time to poll for varName when loading a script in
556 * Safari 2.x before the transaction fails.
565 * Called by the the helper for detecting script load in Safari
567 * @param id {string} the transaction id
570 _finalize: function(id) {
571 YAHOO.log(id + " finalized ", "info", "Get");
572 lang.later(0, null, _finish, id);
576 * Abort a transaction
578 * @param {string|object} either the tId or the object returned from
582 var id = (lang.isString(o)) ? o : o.tId;
585 YAHOO.log("Aborting " + id, "info", "Get");
591 * Fetches and inserts one or more script nodes into the head
592 * of the current document or the document in a specified window.
596 * @param url {string|string[]} the url or urls to the script(s)
597 * @param opts {object} Options:
601 * callback to execute when the script(s) are finished loading
602 * The callback receives an object back with the following
606 * <dd>the window the script(s) were inserted into</dd>
608 * <dd>the data object passed in when the request was made</dd>
610 * <dd>An array containing references to the nodes that were
613 * <dd>A function that, when executed, will remove the nodes
614 * that were inserted</dd>
620 * callback to execute when the script load operation fails
621 * The callback receives an object back with the following
625 * <dd>the window the script(s) were inserted into</dd>
627 * <dd>the data object passed in when the request was made</dd>
629 * <dd>An array containing references to the nodes that were
630 * inserted successfully</dd>
632 * <dd>A function that, when executed, will remove any nodes
633 * that were inserted</dd>
639 * callback to execute when a timeout occurs.
640 * The callback receives an object back with the following
644 * <dd>the window the script(s) were inserted into</dd>
646 * <dd>the data object passed in when the request was made</dd>
648 * <dd>An array containing references to the nodes that were
651 * <dd>A function that, when executed, will remove the nodes
652 * that were inserted</dd>
657 * <dd>the execution context for the callbacks</dd>
659 * <dd>a window other than the one the utility occupies</dd>
662 * setting to true will let the utilities cleanup routine purge
663 * the script once loaded
667 * data that is supplied to the callback when the script(s) are
672 * variable that should be available when a script is finished
673 * loading. Used to help Safari 2.x and below with script load
674 * detection. The type of this property should match what was
675 * passed into the url parameter: if loading a single url, a
676 * string can be supplied. If loading multiple scripts, you
677 * must supply an array that contains the variable name for
680 * <dt>insertBefore</dt>
681 * <dd>node or node id that will become the new node's nextSibling</dd>
684 * <dd>Node charset, deprecated, use 'attributes'</dd>
685 * <dt>attributes</dt>
686 * <dd>A hash of attributes to apply to dynamic nodes.</dd>
688 * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd>
690 * // assumes yahoo, dom, and event are already on the page
691 * YAHOO.util.Get.script(
692 * ["http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js",
693 * "http://yui.yahooapis.com/2.7.0/build/animation/animation-min.js"], {
694 * onSuccess: function(o) {
695 * YAHOO.log(o.data); // foo
696 * new YAHOO.util.DDProxy("dd1"); // also new o.reference("dd1"); would work
697 * this.log("won't cause error because YAHOO is the scope");
698 * this.log(o.nodes.length === 2) // true
699 * // o.purge(); // optionally remove the script nodes immediately
700 * },
701 * onFailure: function(o) {
702 * YAHOO.log("transaction failed");
703 * },
704 * data: "foo",
705 * timeout: 10000, // 10 second timeout
706 * scope: YAHOO,
707 * // win: otherframe // target another window/frame
708 * autopurge: true // allow the utility to choose when to remove the nodes
709 * });
711 * @return {tId: string} an object containing info about the transaction
713 script: function(url, opts) { return _queue("script", url, opts); },
716 * Fetches and inserts one or more css link nodes into the
717 * head of the current document or the document in a specified
721 * @param url {string} the url or urls to the css file(s)
722 * @param opts Options:
726 * callback to execute when the css file(s) are finished loading
727 * The callback receives an object back with the following
730 * <dd>the window the link nodes(s) were inserted into</dd>
732 * <dd>the data object passed in when the request was made</dd>
734 * <dd>An array containing references to the nodes that were
737 * <dd>A function that, when executed, will remove the nodes
738 * that were inserted</dd>
743 * <dd>the execution context for the callbacks</dd>
745 * <dd>a window other than the one the utility occupies</dd>
748 * data that is supplied to the callbacks when the nodes(s) are
751 * <dt>insertBefore</dt>
752 * <dd>node or node id that will become the new node's nextSibling</dd>
754 * <dd>Node charset, deprecated, use 'attributes'</dd>
755 * <dt>attributes</dt>
756 * <dd>A hash of attributes to apply to dynamic nodes.</dd>
759 * YAHOO.util.Get.css("http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css");
762 * YAHOO.util.Get.css(["http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css",
763 * "http://yui.yahooapis.com/2.7.0/build/logger/assets/skins/sam/logger.css"]);
765 * @return {tId: string} an object containing info about the transaction
767 css: function(url, opts) {
768 return _queue("css", url, opts);
773 YAHOO.register("get", YAHOO.util.Get, {version: "2.8.0r4", build: "2449"});