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, charset) {
91 var c = charset || "utf-8";
92 return _node("link", {
93 "id": "yui__dyn_" + (nidx++),
102 * Generates a script node
103 * @method _scriptNode
104 * @param url {string} the url for the script file
105 * @param win {Window} optional window to create the node in
106 * @return {HTMLElement} the generated node
109 var _scriptNode = function(url, win, charset) {
110 var c = charset || "utf-8";
111 return _node("script", {
112 "id": "yui__dyn_" + (nidx++),
113 "type": "text/javascript",
120 * Returns the data payload for callback functions
121 * @method _returnData
124 var _returnData = function(q, msg) {
137 var _get = function(nId, tId) {
139 n = (lang.isString(nId)) ? q.win.document.getElementById(nId) : nId;
141 _fail(tId, "target node not found: " + nId);
148 * The request failed, execute fail handler with whatever
149 * was accomplished. There isn't a failure case at the
150 * moment unless you count aborted transactions
152 * @param id {string} the id of the request
155 var _fail = function(id, msg) {
157 // execute failure callback
159 var sc=q.scope || q.win;
160 q.onFailure.call(sc, _returnData(q, msg));
165 * The request is complete, so executing the requester's callback
167 * @param id {string} the id of the request
170 var _finish = function(id) {
175 var msg = "transaction " + id + " was aborted";
180 // execute success callback
182 var sc=q.scope || q.win;
183 q.onSuccess.call(sc, _returnData(q));
190 * @param id {string} the id of the request
193 var _timeout = function(id) {
197 q.onTimeout.call(sc, _returnData(q));
202 * Loads the next item for a given request
204 * @param id {string} the id of the request
205 * @param loaded {string} the url that was just loaded, if any
208 var _next = function(id, loaded) {
212 // Y.log('cancel timer');
217 var msg = "transaction " + id + " was aborted";
228 // This is the first pass: make sure the url is an array
229 q.url = (lang.isString(q.url)) ? [q.url] : q.url;
231 q.varName = (lang.isString(q.varName)) ? [q.varName] : q.varName;
235 var w=q.win, d=w.document, h=d.getElementsByTagName("head")[0], n;
237 if (q.url.length === 0) {
238 // Safari 2.x workaround - There is no way to know when
239 // a script is ready in versions of Safari prior to 3.x.
240 // Adding an extra node reduces the problem, but doesn't
241 // eliminate it completely because the browser executes
242 // them asynchronously.
243 if (q.type === "script" && ua.webkit && ua.webkit < 420 &&
244 !q.finalpass && !q.varName) {
245 // Add another script node. This does not guarantee that the
246 // scripts will execute in order, but it does appear to fix the
247 // problem on fast connections more effectively than using an
248 // arbitrary timeout. It is possible that the browser does
249 // block subsequent script execution in this case for a limited
251 var extra = _scriptNode(null, q.win, q.charset);
252 extra.innerHTML='YAHOO.util.Get._finalize("' + id + '");';
253 q.nodes.push(extra); h.appendChild(extra);
265 // if the url is undefined, this is probably a trailing comma problem in IE
273 // Y.log('create timer');
274 q.timer = lang.later(q.timeout, q, _timeout, id);
277 if (q.type === "script") {
278 n = _scriptNode(url, w, q.charset);
280 n = _linkNode(url, w, q.charset);
283 // track this node's load progress
284 _track(q.type, n, id, url, w, q.url.length);
286 // add the node to the queue so we can return it to the user supplied callback
289 // add it to the head or insert it before 'insertBefore'
290 if (q.insertBefore) {
291 var s = _get(q.insertBefore, id);
293 s.parentNode.insertBefore(n, s);
300 // FireFox does not support the onload event for link nodes, so there is
301 // no way to make the css requests synchronous. This means that the css
302 // rules in multiple files could be applied out of order in this browser
303 // if a later request returns before an earlier one. Safari too.
304 if ((ua.webkit || ua.gecko) && q.type === "css") {
310 * Removes processed queues and corresponding nodes
314 var _autoPurge = function() {
321 for (var i in queues) {
323 if (q.autopurge && q.finished) {
333 * Removes the nodes for the specified queue
337 var _purge = function(tId) {
340 var n=q.nodes, l=n.length, d=q.win.document,
341 h=d.getElementsByTagName("head")[0];
343 if (q.insertBefore) {
344 var s = _get(q.insertBefore, tId);
350 for (var i=0; i<l; i=i+1) {
359 * Saves the state for the request and begins loading
362 * @param type {string} the type of node to insert
363 * @param url {string} the url to load
364 * @param opts the hash of options for this request
367 var _queue = function(type, url, opts) {
369 var id = "q" + (qidx++);
372 if (qidx % YAHOO.util.Get.PURGE_THRESH === 0) {
376 queues[id] = lang.merge(opts, {
386 q.win = q.win || window;
387 q.scope = q.scope || q.win;
388 q.autopurge = ("autopurge" in q) ? q.autopurge :
389 (type === "script") ? true : false;
391 lang.later(0, q, _next, id);
399 * Detects when a node has been loaded. In the case of
400 * script nodes, this does not guarantee that contained
401 * script is ready to use.
403 * @param type {string} the type of node to track
404 * @param n {HTMLElement} the node to track
405 * @param id {string} the id of the request
406 * @param url {string} the url that is being loaded
407 * @param win {Window} the targeted window
408 * @param qlength the number of remaining items in the queue,
410 * @param trackfn {Function} function to execute when finished
411 * the default is _next
414 var _track = function(type, n, id, url, win, qlength, trackfn) {
415 var f = trackfn || _next;
417 // IE supports the readystatechange event for script and css nodes
419 n.onreadystatechange = function() {
420 var rs = this.readyState;
421 if ("loaded" === rs || "complete" === rs) {
422 n.onreadystatechange = null;
427 // webkit prior to 3.x is problemmatic
428 } else if (ua.webkit) {
430 if (type === "script") {
432 // Safari 3.x supports the load event for script nodes (DOM2)
433 if (ua.webkit >= 420) {
435 n.addEventListener("load", function() {
439 // Nothing can be done with Safari < 3.x except to pause and hope
440 // for the best, particularly after last script is inserted. The
441 // scripts will always execute in the order they arrive, not
442 // necessarily the order in which they were inserted. To support
443 // script nodes with complete reliability in these browsers, script
444 // nodes either need to invoke a function in the window once they
445 // are loaded or the implementer needs to provide a well-known
446 // property that the utility can poll for.
448 // Poll for the existence of the named variable, if it
452 var freq=YAHOO.util.Get.POLL_FREQ;
453 q.maxattempts = YAHOO.util.Get.TIMEOUT/freq;
455 q._cache = q.varName[0].split(".");
456 q.timer = lang.later(freq, q, function(o) {
457 var a=this._cache, l=a.length, w=this.win, i;
458 for (i=0; i<l; i=i+1) {
461 // if we have exausted our attempts, give up
463 if (this.attempts++ > this.maxattempts) {
464 var msg = "Over retry limit, giving up";
479 lang.later(YAHOO.util.Get.POLL_FREQ, null, f, [id, url]);
484 // FireFox and Opera support onload (but not DOM2 in FF) handlers for
485 // script nodes. Opera, but not FF, supports the onload event for link
488 n.onload = function() {
497 * The default poll freqency in ms, when needed
498 * @property POLL_FREQ
506 * The number of request required before an automatic purge.
507 * property PURGE_THRESH
515 * The length time to poll for varName when loading a script in
516 * Safari 2.x before the transaction fails.
525 * Called by the the helper for detecting script load in Safari
527 * @param id {string} the transaction id
530 _finalize: function(id) {
531 lang.later(0, null, _finish, id);
535 * Abort a transaction
537 * @param {string|object} either the tId or the object returned from
541 var id = (lang.isString(o)) ? o : o.tId;
549 * Fetches and inserts one or more script nodes into the head
550 * of the current document or the document in a specified window.
554 * @param url {string|string[]} the url or urls to the script(s)
555 * @param opts {object} Options:
559 * callback to execute when the script(s) are finished loading
560 * The callback receives an object back with the following
564 * <dd>the window the script(s) were inserted into</dd>
566 * <dd>the data object passed in when the request was made</dd>
568 * <dd>An array containing references to the nodes that were
571 * <dd>A function that, when executed, will remove the nodes
572 * that were inserted</dd>
578 * callback to execute when the script load operation fails
579 * The callback receives an object back with the following
583 * <dd>the window the script(s) were inserted into</dd>
585 * <dd>the data object passed in when the request was made</dd>
587 * <dd>An array containing references to the nodes that were
588 * inserted successfully</dd>
590 * <dd>A function that, when executed, will remove any nodes
591 * that were inserted</dd>
597 * callback to execute when a timeout occurs.
598 * The callback receives an object back with the following
602 * <dd>the window the script(s) were inserted into</dd>
604 * <dd>the data object passed in when the request was made</dd>
606 * <dd>An array containing references to the nodes that were
609 * <dd>A function that, when executed, will remove the nodes
610 * that were inserted</dd>
615 * <dd>the execution context for the callbacks</dd>
617 * <dd>a window other than the one the utility occupies</dd>
620 * setting to true will let the utilities cleanup routine purge
621 * the script once loaded
625 * data that is supplied to the callback when the script(s) are
630 * variable that should be available when a script is finished
631 * loading. Used to help Safari 2.x and below with script load
632 * detection. The type of this property should match what was
633 * passed into the url parameter: if loading a single url, a
634 * string can be supplied. If loading multiple scripts, you
635 * must supply an array that contains the variable name for
638 * <dt>insertBefore</dt>
639 * <dd>node or node id that will become the new node's nextSibling</dd>
642 * <dd>Node charset, default utf-8</dd>
644 * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd>
646 * // assumes yahoo, dom, and event are already on the page
647 * YAHOO.util.Get.script(
648 * ["http://yui.yahooapis.com/2.3.1/build/dragdrop/dragdrop-min.js",
649 * "http://yui.yahooapis.com/2.3.1/build/animation/animation-min.js"], {
650 * onSuccess: function(o) {
651 * new YAHOO.util.DDProxy("dd1"); // also new o.reference("dd1"); would work
652 * this.log("won't cause error because YAHOO is the scope");
653 * this.log(o.nodes.length === 2) // true
654 * // o.purge(); // optionally remove the script nodes immediately
655 * },
656 * onFailure: function(o) {
657 * },
658 * data: "foo",
659 * timeout: 10000, // 10 second timeout
660 * scope: YAHOO,
661 * // win: otherframe // target another window/frame
662 * autopurge: true // allow the utility to choose when to remove the nodes
663 * });
665 * @return {tId: string} an object containing info about the transaction
667 script: function(url, opts) { return _queue("script", url, opts); },
670 * Fetches and inserts one or more css link nodes into the
671 * head of the current document or the document in a specified
675 * @param url {string} the url or urls to the css file(s)
676 * @param opts Options:
680 * callback to execute when the css file(s) are finished loading
681 * The callback receives an object back with the following
684 * <dd>the window the link nodes(s) were inserted into</dd>
686 * <dd>the data object passed in when the request was made</dd>
688 * <dd>An array containing references to the nodes that were
691 * <dd>A function that, when executed, will remove the nodes
692 * that were inserted</dd>
697 * <dd>the execution context for the callbacks</dd>
699 * <dd>a window other than the one the utility occupies</dd>
702 * data that is supplied to the callbacks when the nodes(s) are
705 * <dt>insertBefore</dt>
706 * <dd>node or node id that will become the new node's nextSibling</dd>
708 * <dd>Node charset, default utf-8</dd>
711 * YAHOO.util.Get.css("http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css");
714 * YAHOO.util.Get.css(["http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css",
716 * @return {tId: string} an object containing info about the transaction
718 css: function(url, opts) {
719 return _queue("css", url, opts);
724 YAHOO.register("get", YAHOO.util.Get, {version: "2.7.0", build: "1799"});