2 Copyright (c) 2011, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 * Provides a mechanism to fetch remote resources and
9 * insert them into a document
10 * This utility can fetch JavaScript and CSS files, inserting script
11 * tags for script and link tags for CSS. Note, this
12 * is done via the normal browser mechanisms for inserting
13 * these resources and making the content available to
14 * code that would access it. Be careful when retreiving
15 * remote resources. Only use this utility to fetch
16 * files from sites you trust.
23 * Fetches and inserts one or more script or link nodes into the document.
24 * This utility can fetch JavaScript and CSS files, inserting script
25 * tags for script and link tags for CSS. Note, this
26 * is done via the normal browser mechanisms for inserting
27 * these resources and making the content available to
28 * code that would access it. Be careful when retreiving
29 * remote resources. Only use this utility to fetch
30 * files from sites you trust.
32 * @namespace YAHOO.util
33 * @class YAHOO.util.Get
35 YAHOO.util.Get = function() {
38 * hash of queues to manage multiple requests
45 * queue index used to generate transaction ids
53 * node index used to generate unique node ids
61 * interal property used to prevent multiple simultaneous purge
78 * Generates an HTML element, this is not appended to a document
80 * @param type {string} the type of element
81 * @param attr {string} the attributes
82 * @param win {Window} optional window to create the element in
83 * @return {HTMLElement} the generated node
86 _node = function(type, attr, win) {
87 var w = win || window, d=w.document, n=d.createElement(type), i;
90 if (attr.hasOwnProperty(i)) {
91 n.setAttribute(i, attr[i]);
99 * Generates a link node
101 * @param url {string} the url for the css file
102 * @param win {Window} optional window to create the node in
103 * @return {HTMLElement} the generated node
106 _linkNode = function(url, win, attributes) {
109 id: "yui__dyn_" + (nidx++),
116 lang.augmentObject(o, attributes);
119 return _node("link", o, win);
123 * Generates a script node
124 * @method _scriptNode
125 * @param url {string} the url for the script file
126 * @param win {Window} optional window to create the node in
127 * @return {HTMLElement} the generated node
130 _scriptNode = function(url, win, attributes) {
132 id: "yui__dyn_" + (nidx++),
133 type: "text/javascript",
138 lang.augmentObject(o, attributes);
141 return _node("script", o, win);
145 * Returns the data payload for callback functions
146 * @method _returnData
149 _returnData = function(q, msg) {
162 _get = function(nId, tId) {
164 n = (lang.isString(nId)) ? q.win.document.getElementById(nId) : nId;
166 _fail(tId, "target node not found: " + nId);
174 * The request is complete, so executing the requester's callback
176 * @param id {string} the id of the request
179 _finish = function(id) {
180 var q = queues[id], msg, context;
184 msg = "transaction " + id + " was aborted";
189 // execute success callback
191 context = q.scope || q.win;
192 q.onSuccess.call(context, _returnData(q));
199 * @param id {string} the id of the request
202 _timeout = function(id) {
203 var q = queues[id], context;
205 context = q.scope || q;
206 q.onTimeout.call(context, _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 _next = function(id, loaded) {
220 var q = queues[id], w=q.win, d=w.document, h=d.getElementsByTagName("head")[0],
221 n, msg, url, s, extra;
224 // Y.log('cancel timer');
229 msg = "transaction " + id + " was aborted";
240 // This is the first pass: make sure the url is an array
241 q.url = (lang.isString(q.url)) ? [q.url] : q.url;
243 q.varName = (lang.isString(q.varName)) ? [q.varName] : q.varName;
248 if (q.url.length === 0) {
249 // Safari 2.x workaround - There is no way to know when
250 // a script is ready in versions of Safari prior to 3.x.
251 // Adding an extra node reduces the problem, but doesn't
252 // eliminate it completely because the browser executes
253 // them asynchronously.
254 if (q.type === "script" && ua.webkit && ua.webkit < 420 &&
255 !q.finalpass && !q.varName) {
256 // Add another script node. This does not guarantee that the
257 // scripts will execute in order, but it does appear to fix the
258 // problem on fast connections more effectively than using an
259 // arbitrary timeout. It is possible that the browser does
260 // block subsequent script execution in this case for a limited
262 extra = _scriptNode(null, q.win, q.attributes);
263 extra.innerHTML='YAHOO.util.Get._finalize("' + id + '");';
264 q.nodes.push(extra); h.appendChild(extra);
276 // if the url is undefined, this is probably a trailing comma problem in IE
284 // Y.log('create timer');
285 q.timer = lang.later(q.timeout, q, _timeout, id);
288 if (q.type === "script") {
289 n = _scriptNode(url, w, q.attributes);
291 n = _linkNode(url, w, q.attributes);
294 // track this node's load progress
295 _track(q.type, n, id, url, w, q.url.length);
297 // add the node to the queue so we can return it to the user supplied callback
300 // add it to the head or insert it before 'insertBefore'
301 if (q.insertBefore) {
302 s = _get(q.insertBefore, id);
304 s.parentNode.insertBefore(n, s);
311 // FireFox does not support the onload event for link nodes, so there is
312 // no way to make the css requests synchronous. This means that the css
313 // rules in multiple files could be applied out of order in this browser
314 // if a later request returns before an earlier one. Safari too.
315 if ((ua.webkit || ua.gecko) && q.type === "css") {
321 * Removes processed queues and corresponding nodes
325 _autoPurge = function() {
336 if (queues.hasOwnProperty(i)) {
338 if (q.autopurge && q.finished) {
349 * Saves the state for the request and begins loading
352 * @param type {string} the type of node to insert
353 * @param url {string} the url to load
354 * @param opts the hash of options for this request
357 _queue = function(type, url, opts) {
359 var id = "q" + (qidx++), q;
362 if (qidx % YAHOO.util.Get.PURGE_THRESH === 0) {
366 queues[id] = lang.merge(opts, {
376 q.win = q.win || window;
377 q.scope = q.scope || q.win;
378 q.autopurge = ("autopurge" in q) ? q.autopurge :
379 (type === "script") ? true : false;
381 q.attributes = q.attributes || {};
382 q.attributes.charset = opts.charset || q.attributes.charset || 'utf-8';
384 lang.later(0, q, _next, id);
392 * Detects when a node has been loaded. In the case of
393 * script nodes, this does not guarantee that contained
394 * script is ready to use.
396 * @param type {string} the type of node to track
397 * @param n {HTMLElement} the node to track
398 * @param id {string} the id of the request
399 * @param url {string} the url that is being loaded
400 * @param win {Window} the targeted window
401 * @param qlength the number of remaining items in the queue,
403 * @param trackfn {Function} function to execute when finished
404 * the default is _next
407 _track = function(type, n, id, url, win, qlength, trackfn) {
408 var f = trackfn || _next, rs, q, a, freq, w, l, i, msg;
410 // IE supports the readystatechange event for script and css nodes
412 n.onreadystatechange = function() {
413 rs = this.readyState;
414 if ("loaded" === rs || "complete" === rs) {
415 n.onreadystatechange = null;
420 // webkit prior to 3.x is problemmatic
421 } else if (ua.webkit) {
423 if (type === "script") {
425 // Safari 3.x supports the load event for script nodes (DOM2)
426 if (ua.webkit >= 420) {
428 n.addEventListener("load", function() {
432 // Nothing can be done with Safari < 3.x except to pause and hope
433 // for the best, particularly after last script is inserted. The
434 // scripts will always execute in the order they arrive, not
435 // necessarily the order in which they were inserted. To support
436 // script nodes with complete reliability in these browsers, script
437 // nodes either need to invoke a function in the window once they
438 // are loaded or the implementer needs to provide a well-known
439 // property that the utility can poll for.
441 // Poll for the existence of the named variable, if it
445 freq = YAHOO.util.Get.POLL_FREQ;
446 q.maxattempts = YAHOO.util.Get.TIMEOUT/freq;
448 q._cache = q.varName[0].split(".");
449 q.timer = lang.later(freq, q, function(o) {
453 for (i=0; i<l; i=i+1) {
456 // if we have exausted our attempts, give up
458 if (this.attempts++ > this.maxattempts) {
459 msg = "Over retry limit, giving up";
474 lang.later(YAHOO.util.Get.POLL_FREQ, null, f, [id, url]);
479 // FireFox and Opera support onload (but not DOM2 in FF) handlers for
480 // script nodes. Opera, but not FF, supports the onload event for link
483 n.onload = function() {
490 * The request failed, execute fail handler with whatever
491 * was accomplished. There isn't a failure case at the
492 * moment unless you count aborted transactions
494 * @param id {string} the id of the request
497 _fail = function(id, msg) {
498 var q = queues[id], context;
499 // execute failure callback
501 context = q.scope || q.win;
502 q.onFailure.call(context, _returnData(q, msg));
507 * Removes the nodes for the specified queue
511 _purge = function(tId) {
518 h = d.getElementsByTagName("head")[0],
521 if (q.insertBefore) {
522 sib = _get(q.insertBefore, tId);
528 for (i=0; i<l; i=i+1) {
530 if (node.clearAttributes) {
531 node.clearAttributes();
534 if (node.hasOwnProperty(attr)) {
551 * The default poll freqency in ms, when needed
552 * @property POLL_FREQ
560 * The number of request required before an automatic purge.
561 * property PURGE_THRESH
569 * The length time to poll for varName when loading a script in
570 * Safari 2.x before the transaction fails.
579 * Called by the the helper for detecting script load in Safari
581 * @param id {string} the transaction id
584 _finalize: function(id) {
585 lang.later(0, null, _finish, id);
589 * Abort a transaction
591 * @param {string|object} either the tId or the object returned from
595 var id = (lang.isString(o)) ? o : o.tId,
603 * Fetches and inserts one or more script nodes into the head
604 * of the current document or the document in a specified window.
608 * @param url {string|string[]} the url or urls to the script(s)
609 * @param opts {object} Options:
613 * callback to execute when the script(s) are finished loading
614 * The callback receives an object back with the following
618 * <dd>the window the script(s) were inserted into</dd>
620 * <dd>the data object passed in when the request was made</dd>
622 * <dd>An array containing references to the nodes that were
625 * <dd>A function that, when executed, will remove the nodes
626 * that were inserted</dd>
632 * callback to execute when the script load operation fails
633 * The callback receives an object back with the following
637 * <dd>the window the script(s) were inserted into</dd>
639 * <dd>the data object passed in when the request was made</dd>
641 * <dd>An array containing references to the nodes that were
642 * inserted successfully</dd>
644 * <dd>A function that, when executed, will remove any nodes
645 * that were inserted</dd>
651 * callback to execute when a timeout occurs.
652 * The callback receives an object back with the following
656 * <dd>the window the script(s) were inserted into</dd>
658 * <dd>the data object passed in when the request was made</dd>
660 * <dd>An array containing references to the nodes that were
663 * <dd>A function that, when executed, will remove the nodes
664 * that were inserted</dd>
669 * <dd>the execution context for the callbacks</dd>
671 * <dd>a window other than the one the utility occupies</dd>
674 * setting to true will let the utilities cleanup routine purge
675 * the script once loaded
679 * data that is supplied to the callback when the script(s) are
684 * variable that should be available when a script is finished
685 * loading. Used to help Safari 2.x and below with script load
686 * detection. The type of this property should match what was
687 * passed into the url parameter: if loading a single url, a
688 * string can be supplied. If loading multiple scripts, you
689 * must supply an array that contains the variable name for
692 * <dt>insertBefore</dt>
693 * <dd>node or node id that will become the new node's nextSibling</dd>
696 * <dd>Node charset, deprecated, use 'attributes'</dd>
697 * <dt>attributes</dt>
698 * <dd>A hash of attributes to apply to dynamic nodes.</dd>
700 * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd>
702 * // assumes yahoo, dom, and event are already on the page
703 * YAHOO.util.Get.script(
704 * ["http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js",
705 * "http://yui.yahooapis.com/2.7.0/build/animation/animation-min.js"], {
706 * onSuccess: function(o) {
707 * new YAHOO.util.DDProxy("dd1"); // also new o.reference("dd1"); would work
708 * this.log("won't cause error because YAHOO is the scope");
709 * this.log(o.nodes.length === 2) // true
710 * // o.purge(); // optionally remove the script nodes immediately
711 * },
712 * onFailure: function(o) {
713 * },
714 * data: "foo",
715 * timeout: 10000, // 10 second timeout
716 * scope: YAHOO,
717 * // win: otherframe // target another window/frame
718 * autopurge: true // allow the utility to choose when to remove the nodes
719 * });
721 * @return {tId: string} an object containing info about the transaction
723 script: function(url, opts) { return _queue("script", url, opts); },
726 * Fetches and inserts one or more css link nodes into the
727 * head of the current document or the document in a specified
731 * @param url {string} the url or urls to the css file(s)
732 * @param opts Options:
736 * callback to execute when the css file(s) are finished loading
737 * The callback receives an object back with the following
740 * <dd>the window the link nodes(s) were inserted into</dd>
742 * <dd>the data object passed in when the request was made</dd>
744 * <dd>An array containing references to the nodes that were
747 * <dd>A function that, when executed, will remove the nodes
748 * that were inserted</dd>
753 * <dd>the execution context for the callbacks</dd>
755 * <dd>a window other than the one the utility occupies</dd>
758 * data that is supplied to the callbacks when the nodes(s) are
761 * <dt>insertBefore</dt>
762 * <dd>node or node id that will become the new node's nextSibling</dd>
764 * <dd>Node charset, deprecated, use 'attributes'</dd>
765 * <dt>attributes</dt>
766 * <dd>A hash of attributes to apply to dynamic nodes.</dd>
769 * YAHOO.util.Get.css("http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css");
772 * YAHOO.util.Get.css(["http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css",
774 * @return {tId: string} an object containing info about the transaction
776 css: function(url, opts) {
777 return _queue("css", url, opts);
782 YAHOO.register("get", YAHOO.util.Get, {version: "2.9.0", build: "2800"});