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) {
156 YAHOO.log("get failure: " + msg, "warn", "Get");
158 // execute failure callback
160 var sc=q.scope || q.win;
161 q.onFailure.call(sc, _returnData(q, msg));
166 * The request is complete, so executing the requester's callback
168 * @param id {string} the id of the request
171 var _finish = function(id) {
172 YAHOO.log("Finishing transaction " + id);
177 var msg = "transaction " + id + " was aborted";
182 // execute success callback
184 var sc=q.scope || q.win;
185 q.onSuccess.call(sc, _returnData(q));
192 * @param id {string} the id of the request
195 var _timeout = function(id) {
196 YAHOO.log("Timeout " + id, "info", "get");
200 q.onTimeout.call(sc, _returnData(q));
205 * Loads the next item for a given request
207 * @param id {string} the id of the request
208 * @param loaded {string} the url that was just loaded, if any
211 var _next = function(id, loaded) {
212 YAHOO.log("_next: " + id + ", loaded: " + loaded, "info", "Get");
216 // Y.log('cancel timer');
221 var msg = "transaction " + id + " was aborted";
232 // This is the first pass: make sure the url is an array
233 q.url = (lang.isString(q.url)) ? [q.url] : q.url;
235 q.varName = (lang.isString(q.varName)) ? [q.varName] : q.varName;
239 var w=q.win, d=w.document, h=d.getElementsByTagName("head")[0], n;
241 if (q.url.length === 0) {
242 // Safari 2.x workaround - There is no way to know when
243 // a script is ready in versions of Safari prior to 3.x.
244 // Adding an extra node reduces the problem, but doesn't
245 // eliminate it completely because the browser executes
246 // them asynchronously.
247 if (q.type === "script" && ua.webkit && ua.webkit < 420 &&
248 !q.finalpass && !q.varName) {
249 // Add another script node. This does not guarantee that the
250 // scripts will execute in order, but it does appear to fix the
251 // problem on fast connections more effectively than using an
252 // arbitrary timeout. It is possible that the browser does
253 // block subsequent script execution in this case for a limited
255 var extra = _scriptNode(null, q.win, q.charset);
256 extra.innerHTML='YAHOO.util.Get._finalize("' + id + '");';
257 q.nodes.push(extra); h.appendChild(extra);
269 // if the url is undefined, this is probably a trailing comma problem in IE
272 YAHOO.log('skipping empty url');
276 YAHOO.log("attempting to load " + url, "info", "Get");
279 // Y.log('create timer');
280 q.timer = lang.later(q.timeout, q, _timeout, id);
283 if (q.type === "script") {
284 n = _scriptNode(url, w, q.charset);
286 n = _linkNode(url, w, q.charset);
289 // track this node's load progress
290 _track(q.type, n, id, url, w, q.url.length);
292 // add the node to the queue so we can return it to the user supplied callback
295 // add it to the head or insert it before 'insertBefore'
296 if (q.insertBefore) {
297 var s = _get(q.insertBefore, id);
299 s.parentNode.insertBefore(n, s);
305 YAHOO.log("Appending node: " + url, "info", "Get");
307 // FireFox does not support the onload event for link nodes, so there is
308 // no way to make the css requests synchronous. This means that the css
309 // rules in multiple files could be applied out of order in this browser
310 // if a later request returns before an earlier one. Safari too.
311 if ((ua.webkit || ua.gecko) && q.type === "css") {
317 * Removes processed queues and corresponding nodes
321 var _autoPurge = function() {
328 for (var i in queues) {
330 if (q.autopurge && q.finished) {
340 * Removes the nodes for the specified queue
344 var _purge = function(tId) {
347 var n=q.nodes, l=n.length, d=q.win.document,
348 h=d.getElementsByTagName("head")[0];
350 if (q.insertBefore) {
351 var s = _get(q.insertBefore, tId);
357 for (var i=0; i<l; i=i+1) {
366 * Saves the state for the request and begins loading
369 * @param type {string} the type of node to insert
370 * @param url {string} the url to load
371 * @param opts the hash of options for this request
374 var _queue = function(type, url, opts) {
376 var id = "q" + (qidx++);
379 if (qidx % YAHOO.util.Get.PURGE_THRESH === 0) {
383 queues[id] = lang.merge(opts, {
393 q.win = q.win || window;
394 q.scope = q.scope || q.win;
395 q.autopurge = ("autopurge" in q) ? q.autopurge :
396 (type === "script") ? true : false;
398 lang.later(0, q, _next, id);
406 * Detects when a node has been loaded. In the case of
407 * script nodes, this does not guarantee that contained
408 * script is ready to use.
410 * @param type {string} the type of node to track
411 * @param n {HTMLElement} the node to track
412 * @param id {string} the id of the request
413 * @param url {string} the url that is being loaded
414 * @param win {Window} the targeted window
415 * @param qlength the number of remaining items in the queue,
417 * @param trackfn {Function} function to execute when finished
418 * the default is _next
421 var _track = function(type, n, id, url, win, qlength, trackfn) {
422 var f = trackfn || _next;
424 // IE supports the readystatechange event for script and css nodes
426 n.onreadystatechange = function() {
427 var rs = this.readyState;
428 if ("loaded" === rs || "complete" === rs) {
429 YAHOO.log(id + " onload " + url, "info", "Get");
430 n.onreadystatechange = null;
435 // webkit prior to 3.x is problemmatic
436 } else if (ua.webkit) {
438 if (type === "script") {
440 // Safari 3.x supports the load event for script nodes (DOM2)
441 if (ua.webkit >= 420) {
443 n.addEventListener("load", function() {
444 YAHOO.log(id + " DOM2 onload " + url, "info", "Get");
448 // Nothing can be done with Safari < 3.x except to pause and hope
449 // for the best, particularly after last script is inserted. The
450 // scripts will always execute in the order they arrive, not
451 // necessarily the order in which they were inserted. To support
452 // script nodes with complete reliability in these browsers, script
453 // nodes either need to invoke a function in the window once they
454 // are loaded or the implementer needs to provide a well-known
455 // property that the utility can poll for.
457 // Poll for the existence of the named variable, if it
461 var freq=YAHOO.util.Get.POLL_FREQ;
462 YAHOO.log("Polling for " + q.varName[0]);
463 q.maxattempts = YAHOO.util.Get.TIMEOUT/freq;
465 q._cache = q.varName[0].split(".");
466 q.timer = lang.later(freq, q, function(o) {
467 var a=this._cache, l=a.length, w=this.win, i;
468 for (i=0; i<l; i=i+1) {
471 // if we have exausted our attempts, give up
473 if (this.attempts++ > this.maxattempts) {
474 var msg = "Over retry limit, giving up";
478 YAHOO.log(a[i] + " failed, retrying");
484 YAHOO.log("Safari poll complete");
491 lang.later(YAHOO.util.Get.POLL_FREQ, null, f, [id, url]);
496 // FireFox and Opera support onload (but not DOM2 in FF) handlers for
497 // script nodes. Opera, but not FF, supports the onload event for link
500 n.onload = function() {
501 YAHOO.log(id + " onload " + url, "info", "Get");
510 * The default poll freqency in ms, when needed
511 * @property POLL_FREQ
519 * The number of request required before an automatic purge.
520 * property PURGE_THRESH
528 * The length time to poll for varName when loading a script in
529 * Safari 2.x before the transaction fails.
538 * Called by the the helper for detecting script load in Safari
540 * @param id {string} the transaction id
543 _finalize: function(id) {
544 YAHOO.log(id + " finalized ", "info", "Get");
545 lang.later(0, null, _finish, id);
549 * Abort a transaction
551 * @param {string|object} either the tId or the object returned from
555 var id = (lang.isString(o)) ? o : o.tId;
558 YAHOO.log("Aborting " + id, "info", "Get");
564 * Fetches and inserts one or more script nodes into the head
565 * of the current document or the document in a specified window.
569 * @param url {string|string[]} the url or urls to the script(s)
570 * @param opts {object} Options:
574 * callback to execute when the script(s) are finished loading
575 * The callback receives an object back with the following
579 * <dd>the window the script(s) were inserted into</dd>
581 * <dd>the data object passed in when the request was made</dd>
583 * <dd>An array containing references to the nodes that were
586 * <dd>A function that, when executed, will remove the nodes
587 * that were inserted</dd>
593 * callback to execute when the script load operation fails
594 * The callback receives an object back with the following
598 * <dd>the window the script(s) were inserted into</dd>
600 * <dd>the data object passed in when the request was made</dd>
602 * <dd>An array containing references to the nodes that were
603 * inserted successfully</dd>
605 * <dd>A function that, when executed, will remove any nodes
606 * that were inserted</dd>
612 * callback to execute when a timeout occurs.
613 * The callback receives an object back with the following
617 * <dd>the window the script(s) were inserted into</dd>
619 * <dd>the data object passed in when the request was made</dd>
621 * <dd>An array containing references to the nodes that were
624 * <dd>A function that, when executed, will remove the nodes
625 * that were inserted</dd>
630 * <dd>the execution context for the callbacks</dd>
632 * <dd>a window other than the one the utility occupies</dd>
635 * setting to true will let the utilities cleanup routine purge
636 * the script once loaded
640 * data that is supplied to the callback when the script(s) are
645 * variable that should be available when a script is finished
646 * loading. Used to help Safari 2.x and below with script load
647 * detection. The type of this property should match what was
648 * passed into the url parameter: if loading a single url, a
649 * string can be supplied. If loading multiple scripts, you
650 * must supply an array that contains the variable name for
653 * <dt>insertBefore</dt>
654 * <dd>node or node id that will become the new node's nextSibling</dd>
657 * <dd>Node charset, default utf-8</dd>
659 * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd>
661 * // assumes yahoo, dom, and event are already on the page
662 * YAHOO.util.Get.script(
663 * ["http://yui.yahooapis.com/2.3.1/build/dragdrop/dragdrop-min.js",
664 * "http://yui.yahooapis.com/2.3.1/build/animation/animation-min.js"], {
665 * onSuccess: function(o) {
666 * YAHOO.log(o.data); // foo
667 * new YAHOO.util.DDProxy("dd1"); // also new o.reference("dd1"); would work
668 * this.log("won't cause error because YAHOO is the scope");
669 * this.log(o.nodes.length === 2) // true
670 * // o.purge(); // optionally remove the script nodes immediately
671 * },
672 * onFailure: function(o) {
673 * YAHOO.log("transaction failed");
674 * },
675 * data: "foo",
676 * timeout: 10000, // 10 second timeout
677 * scope: YAHOO,
678 * // win: otherframe // target another window/frame
679 * autopurge: true // allow the utility to choose when to remove the nodes
680 * });
682 * @return {tId: string} an object containing info about the transaction
684 script: function(url, opts) { return _queue("script", url, opts); },
687 * Fetches and inserts one or more css link nodes into the
688 * head of the current document or the document in a specified
692 * @param url {string} the url or urls to the css file(s)
693 * @param opts Options:
697 * callback to execute when the css file(s) are finished loading
698 * The callback receives an object back with the following
701 * <dd>the window the link nodes(s) were inserted into</dd>
703 * <dd>the data object passed in when the request was made</dd>
705 * <dd>An array containing references to the nodes that were
708 * <dd>A function that, when executed, will remove the nodes
709 * that were inserted</dd>
714 * <dd>the execution context for the callbacks</dd>
716 * <dd>a window other than the one the utility occupies</dd>
719 * data that is supplied to the callbacks when the nodes(s) are
722 * <dt>insertBefore</dt>
723 * <dd>node or node id that will become the new node's nextSibling</dd>
725 * <dd>Node charset, default utf-8</dd>
728 * YAHOO.util.Get.css("http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css");
731 * YAHOO.util.Get.css(["http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css",
732 * "http://yui.yahooapis.com/2.3.1/build/logger/assets/skins/sam/logger.css"]);
734 * @return {tId: string} an object containing info about the transaction
736 css: function(url, opts) {
737 return _queue("css", url, opts);
742 YAHOO.register("get", YAHOO.util.Get, {version: "2.7.0", build: "1799"});