]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/yui/build/get/get.js
Release 6.5.0
[Github/sugarcrm.git] / include / javascript / yui / build / get / get.js
1 /*
2 Copyright (c) 2011, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
5 version: 2.9.0
6 */
7 /**
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.
17  *
18  * @module get
19  * @requires yahoo
20  */
21
22 /**
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.
31  *
32  * @namespace YAHOO.util
33  * @class YAHOO.util.Get
34  */
35 YAHOO.util.Get = function() {
36
37     /**
38      * hash of queues to manage multiple requests
39      * @property queues
40      * @private
41      */
42     var queues={},
43
44     /**
45      * queue index used to generate transaction ids
46      * @property qidx
47      * @type int
48      * @private
49      */
50         qidx=0,
51
52     /**
53      * node index used to generate unique node ids
54      * @property nidx
55      * @type int
56      * @private
57      */
58         nidx=0,
59
60     /**
61      * interal property used to prevent multiple simultaneous purge
62      * processes
63      * @property purging
64      * @type boolean
65      * @private
66      */
67         _purging=false,
68
69         ua=YAHOO.env.ua,
70
71         lang=YAHOO.lang,
72
73     _fail,
74     _purge,
75     _track,
76
77     /**
78      * Generates an HTML element, this is not appended to a document
79      * @method _node
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
84      * @private
85      */
86     _node = function(type, attr, win) {
87         var w = win || window, d=w.document, n=d.createElement(type), i;
88
89         for (i in attr) {
90             if (attr.hasOwnProperty(i)) {
91                 n.setAttribute(i, attr[i]);
92             }
93         }
94
95         return n;
96     },
97
98     /**
99      * Generates a link node
100      * @method _linkNode
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
104      * @private
105      */
106     _linkNode = function(url, win, attributes) {
107
108         var o = {
109             id:   "yui__dyn_" + (nidx++),
110             type: "text/css",
111             rel:  "stylesheet",
112             href: url
113         };
114
115         if (attributes) {
116             lang.augmentObject(o, attributes);
117         }
118
119         return _node("link", o, win);
120     },
121
122     /**
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
128      * @private
129      */
130     _scriptNode = function(url, win, attributes) {
131         var o = {
132             id:   "yui__dyn_" + (nidx++),
133             type: "text/javascript",
134             src:  url
135         };
136
137         if (attributes) {
138             lang.augmentObject(o, attributes);
139         }
140
141         return _node("script", o, win);
142     },
143
144     /**
145      * Returns the data payload for callback functions
146      * @method _returnData
147      * @private
148      */
149     _returnData = function(q, msg) {
150         return {
151                 tId: q.tId,
152                 win: q.win,
153                 data: q.data,
154                 nodes: q.nodes,
155                 msg: msg,
156                 purge: function() {
157                     _purge(this.tId);
158                 }
159             };
160     },
161
162     _get = function(nId, tId) {
163         var q = queues[tId],
164             n = (lang.isString(nId)) ? q.win.document.getElementById(nId) : nId;
165         if (!n) {
166             _fail(tId, "target node not found: " + nId);
167         }
168
169         return n;
170     },
171
172
173     /**
174      * The request is complete, so executing the requester's callback
175      * @method _finish
176      * @param id {string} the id of the request
177      * @private
178      */
179     _finish = function(id) {
180         var q = queues[id], msg, context;
181         q.finished = true;
182
183         if (q.aborted) {
184             msg = "transaction " + id + " was aborted";
185             _fail(id, msg);
186             return;
187         }
188
189         // execute success callback
190         if (q.onSuccess) {
191             context = q.scope || q.win;
192             q.onSuccess.call(context, _returnData(q));
193         }
194     },
195
196     /**
197      * Timeout detected
198      * @method _timeout
199      * @param id {string} the id of the request
200      * @private
201      */
202     _timeout = function(id) {
203         var q = queues[id], context;
204         if (q.onTimeout) {
205             context = q.scope || q;
206             q.onTimeout.call(context, _returnData(q));
207         }
208     },
209
210     /**
211      * Loads the next item for a given request
212      * @method _next
213      * @param id {string} the id of the request
214      * @param loaded {string} the url that was just loaded, if any
215      * @private
216      */
217     _next = function(id, loaded) {
218
219
220         var q = queues[id], w=q.win, d=w.document, h=d.getElementsByTagName("head")[0],
221             n, msg, url, s, extra;
222
223         if (q.timer) {
224             // Y.log('cancel timer');
225             q.timer.cancel();
226         }
227
228         if (q.aborted) {
229             msg = "transaction " + id + " was aborted";
230             _fail(id, msg);
231             return;
232         }
233
234         if (loaded) {
235             q.url.shift();
236             if (q.varName) {
237                 q.varName.shift();
238             }
239         } else {
240             // This is the first pass: make sure the url is an array
241             q.url = (lang.isString(q.url)) ? [q.url] : q.url;
242             if (q.varName) {
243                 q.varName = (lang.isString(q.varName)) ? [q.varName] : q.varName;
244             }
245         }
246
247
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
261                 // time.
262                 extra = _scriptNode(null, q.win, q.attributes);
263                 extra.innerHTML='YAHOO.util.Get._finalize("' + id + '");';
264                 q.nodes.push(extra); h.appendChild(extra);
265
266             } else {
267                 _finish(id);
268             }
269
270             return;
271         }
272
273
274         url = q.url[0];
275
276         // if the url is undefined, this is probably a trailing comma problem in IE
277         if (!url) {
278             q.url.shift();
279             return _next(id);
280         }
281
282
283         if (q.timeout) {
284             // Y.log('create timer');
285             q.timer = lang.later(q.timeout, q, _timeout, id);
286         }
287
288         if (q.type === "script") {
289             n = _scriptNode(url, w, q.attributes);
290         } else {
291             n = _linkNode(url, w, q.attributes);
292         }
293
294         // track this node's load progress
295         _track(q.type, n, id, url, w, q.url.length);
296
297         // add the node to the queue so we can return it to the user supplied callback
298         q.nodes.push(n);
299
300         // add it to the head or insert it before 'insertBefore'
301         if (q.insertBefore) {
302             s = _get(q.insertBefore, id);
303             if (s) {
304                 s.parentNode.insertBefore(n, s);
305             }
306         } else {
307             h.appendChild(n);
308         }
309
310
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") {
316             _next(id, url);
317         }
318     },
319
320     /**
321      * Removes processed queues and corresponding nodes
322      * @method _autoPurge
323      * @private
324      */
325     _autoPurge = function() {
326
327         if (_purging) {
328             return;
329         }
330
331         _purging = true;
332
333         var i, q;
334
335         for (i in queues) {
336             if (queues.hasOwnProperty(i)) {
337                 q = queues[i];
338                 if (q.autopurge && q.finished) {
339                     _purge(q.tId);
340                     delete queues[i];
341                 }
342             }
343         }
344
345         _purging = false;
346     },
347
348     /**
349      * Saves the state for the request and begins loading
350      * the requested urls
351      * @method queue
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
355      * @private
356      */
357     _queue = function(type, url, opts) {
358
359         var id = "q" + (qidx++), q;
360         opts = opts || {};
361
362         if (qidx % YAHOO.util.Get.PURGE_THRESH === 0) {
363             _autoPurge();
364         }
365
366         queues[id] = lang.merge(opts, {
367             tId: id,
368             type: type,
369             url: url,
370             finished: false,
371             aborted: false,
372             nodes: []
373         });
374
375         q = queues[id];
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;
380
381         q.attributes = q.attributes || {};
382         q.attributes.charset = opts.charset || q.attributes.charset || 'utf-8';
383
384         lang.later(0, q, _next, id);
385
386         return {
387             tId: id
388         };
389     };
390
391     /**
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.
395      * @method _track
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,
402      * including this one
403      * @param trackfn {Function} function to execute when finished
404      * the default is _next
405      * @private
406      */
407     _track = function(type, n, id, url, win, qlength, trackfn) {
408         var f = trackfn || _next, rs, q, a, freq, w, l, i, msg;
409
410         // IE supports the readystatechange event for script and css nodes
411         if (ua.ie) {
412             n.onreadystatechange = function() {
413                 rs = this.readyState;
414                 if ("loaded" === rs || "complete" === rs) {
415                     n.onreadystatechange = null;
416                     f(id, url);
417                 }
418             };
419
420         // webkit prior to 3.x is problemmatic
421         } else if (ua.webkit) {
422
423             if (type === "script") {
424
425                 // Safari 3.x supports the load event for script nodes (DOM2)
426                 if (ua.webkit >= 420) {
427
428                     n.addEventListener("load", function() {
429                         f(id, url);
430                     });
431
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.
440                 } else {
441                     // Poll for the existence of the named variable, if it
442                     // was supplied.
443                     q = queues[id];
444                     if (q.varName) {
445                         freq = YAHOO.util.Get.POLL_FREQ;
446                         q.maxattempts = YAHOO.util.Get.TIMEOUT/freq;
447                         q.attempts = 0;
448                         q._cache = q.varName[0].split(".");
449                         q.timer = lang.later(freq, q, function(o) {
450                             a = this._cache;
451                             l = a.length;
452                             w = this.win;
453                             for (i=0; i<l; i=i+1) {
454                                 w = w[a[i]];
455                                 if (!w) {
456                                     // if we have exausted our attempts, give up
457                                     this.attempts++;
458                                     if (this.attempts++ > this.maxattempts) {
459                                         msg = "Over retry limit, giving up";
460                                         q.timer.cancel();
461                                         _fail(id, msg);
462                                     } else {
463                                     }
464                                     return;
465                                 }
466                             }
467
468
469                             q.timer.cancel();
470                             f(id, url);
471
472                         }, null, true);
473                     } else {
474                         lang.later(YAHOO.util.Get.POLL_FREQ, null, f, [id, url]);
475                     }
476                 }
477             }
478
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
481         // nodes.
482         } else {
483             n.onload = function() {
484                 f(id, url);
485             };
486         }
487     };
488
489     /*
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
493      * @method _fail
494      * @param id {string} the id of the request
495      * @private
496      */
497     _fail = function(id, msg) {
498         var q = queues[id], context;
499         // execute failure callback
500         if (q.onFailure) {
501             context = q.scope || q.win;
502             q.onFailure.call(context, _returnData(q, msg));
503         }
504     };
505
506     /**
507      * Removes the nodes for the specified queue
508      * @method _purge
509      * @private
510      */
511     _purge = function(tId) {
512         if (queues[tId]) {
513
514             var q     = queues[tId],
515                 nodes = q.nodes,
516                 l     = nodes.length,
517                 d     = q.win.document,
518                 h     = d.getElementsByTagName("head")[0],
519                 sib, i, node, attr;
520
521             if (q.insertBefore) {
522                 sib = _get(q.insertBefore, tId);
523                 if (sib) {
524                     h = sib.parentNode;
525                 }
526             }
527
528             for (i=0; i<l; i=i+1) {
529                 node = nodes[i];
530                 if (node.clearAttributes) {
531                     node.clearAttributes();
532                 } else {
533                     for (attr in node) {
534                         if (node.hasOwnProperty(attr)) {
535                             delete node[attr];
536                         }
537                     }
538                 }
539
540                 h.removeChild(node);
541             }
542
543             q.nodes = [];
544         }
545     };
546
547
548     return {
549
550         /**
551          * The default poll freqency in ms, when needed
552          * @property POLL_FREQ
553          * @static
554          * @type int
555          * @default 10
556          */
557         POLL_FREQ: 10,
558
559         /**
560          * The number of request required before an automatic purge.
561          * property PURGE_THRESH
562          * @static
563          * @type int
564          * @default 20
565          */
566         PURGE_THRESH: 20,
567
568         /**
569          * The length time to poll for varName when loading a script in
570          * Safari 2.x before the transaction fails.
571          * property TIMEOUT
572          * @static
573          * @type int
574          * @default 2000
575          */
576         TIMEOUT: 2000,
577
578         /**
579          * Called by the the helper for detecting script load in Safari
580          * @method _finalize
581          * @param id {string} the transaction id
582          * @private
583          */
584         _finalize: function(id) {
585             lang.later(0, null, _finish, id);
586         },
587
588         /**
589          * Abort a transaction
590          * @method abort
591          * @param {string|object} either the tId or the object returned from
592          * script() or css()
593          */
594         abort: function(o) {
595             var id = (lang.isString(o)) ? o : o.tId,
596                 q = queues[id];
597             if (q) {
598                 q.aborted = true;
599             }
600         },
601
602         /**
603          * Fetches and inserts one or more script nodes into the head
604          * of the current document or the document in a specified window.
605          *
606          * @method script
607          * @static
608          * @param url {string|string[]} the url or urls to the script(s)
609          * @param opts {object} Options:
610          * <dl>
611          * <dt>onSuccess</dt>
612          * <dd>
613          * callback to execute when the script(s) are finished loading
614          * The callback receives an object back with the following
615          * data:
616          * <dl>
617          * <dt>win</dt>
618          * <dd>the window the script(s) were inserted into</dd>
619          * <dt>data</dt>
620          * <dd>the data object passed in when the request was made</dd>
621          * <dt>nodes</dt>
622          * <dd>An array containing references to the nodes that were
623          * inserted</dd>
624          * <dt>purge</dt>
625          * <dd>A function that, when executed, will remove the nodes
626          * that were inserted</dd>
627          * <dt>
628          * </dl>
629          * </dd>
630          * <dt>onFailure</dt>
631          * <dd>
632          * callback to execute when the script load operation fails
633          * The callback receives an object back with the following
634          * data:
635          * <dl>
636          * <dt>win</dt>
637          * <dd>the window the script(s) were inserted into</dd>
638          * <dt>data</dt>
639          * <dd>the data object passed in when the request was made</dd>
640          * <dt>nodes</dt>
641          * <dd>An array containing references to the nodes that were
642          * inserted successfully</dd>
643          * <dt>purge</dt>
644          * <dd>A function that, when executed, will remove any nodes
645          * that were inserted</dd>
646          * <dt>
647          * </dl>
648          * </dd>
649          * <dt>onTimeout</dt>
650          * <dd>
651          * callback to execute when a timeout occurs.
652          * The callback receives an object back with the following
653          * data:
654          * <dl>
655          * <dt>win</dt>
656          * <dd>the window the script(s) were inserted into</dd>
657          * <dt>data</dt>
658          * <dd>the data object passed in when the request was made</dd>
659          * <dt>nodes</dt>
660          * <dd>An array containing references to the nodes that were
661          * inserted</dd>
662          * <dt>purge</dt>
663          * <dd>A function that, when executed, will remove the nodes
664          * that were inserted</dd>
665          * <dt>
666          * </dl>
667          * </dd>
668          * <dt>scope</dt>
669          * <dd>the execution context for the callbacks</dd>
670          * <dt>win</dt>
671          * <dd>a window other than the one the utility occupies</dd>
672          * <dt>autopurge</dt>
673          * <dd>
674          * setting to true will let the utilities cleanup routine purge
675          * the script once loaded
676          * </dd>
677          * <dt>data</dt>
678          * <dd>
679          * data that is supplied to the callback when the script(s) are
680          * loaded.
681          * </dd>
682          * <dt>varName</dt>
683          * <dd>
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
690          * each script.
691          * </dd>
692          * <dt>insertBefore</dt>
693          * <dd>node or node id that will become the new node's nextSibling</dd>
694          * </dl>
695          * <dt>charset</dt>
696          * <dd>Node charset, deprecated, use 'attributes'</dd>
697          * <dt>attributes</dt>
698          * <dd>A hash of attributes to apply to dynamic nodes.</dd>
699          * <dt>timeout</dt>
700          * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd>
701          * <pre>
702          * // assumes yahoo, dom, and event are already on the page
703          * &nbsp;&nbsp;YAHOO.util.Get.script(
704          * &nbsp;&nbsp;["http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js",
705          * &nbsp;&nbsp;&nbsp;"http://yui.yahooapis.com/2.7.0/build/animation/animation-min.js"], &#123;
706          * &nbsp;&nbsp;&nbsp;&nbsp;onSuccess: function(o) &#123;
707          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new YAHOO.util.DDProxy("dd1"); // also new o.reference("dd1"); would work
708          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.log("won't cause error because YAHOO is the scope");
709          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.log(o.nodes.length === 2) // true
710          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// o.purge(); // optionally remove the script nodes immediately
711          * &nbsp;&nbsp;&nbsp;&nbsp;&#125;,
712          * &nbsp;&nbsp;&nbsp;&nbsp;onFailure: function(o) &#123;
713          * &nbsp;&nbsp;&nbsp;&nbsp;&#125;,
714          * &nbsp;&nbsp;&nbsp;&nbsp;data: "foo",
715          * &nbsp;&nbsp;&nbsp;&nbsp;timeout: 10000, // 10 second timeout
716          * &nbsp;&nbsp;&nbsp;&nbsp;scope: YAHOO,
717          * &nbsp;&nbsp;&nbsp;&nbsp;// win: otherframe // target another window/frame
718          * &nbsp;&nbsp;&nbsp;&nbsp;autopurge: true // allow the utility to choose when to remove the nodes
719          * &nbsp;&nbsp;&#125;);
720          * </pre>
721          * @return {tId: string} an object containing info about the transaction
722          */
723         script: function(url, opts) { return _queue("script", url, opts); },
724
725         /**
726          * Fetches and inserts one or more css link nodes into the
727          * head of the current document or the document in a specified
728          * window.
729          * @method css
730          * @static
731          * @param url {string} the url or urls to the css file(s)
732          * @param opts Options:
733          * <dl>
734          * <dt>onSuccess</dt>
735          * <dd>
736          * callback to execute when the css file(s) are finished loading
737          * The callback receives an object back with the following
738          * data:
739          * <dl>win</dl>
740          * <dd>the window the link nodes(s) were inserted into</dd>
741          * <dt>data</dt>
742          * <dd>the data object passed in when the request was made</dd>
743          * <dt>nodes</dt>
744          * <dd>An array containing references to the nodes that were
745          * inserted</dd>
746          * <dt>purge</dt>
747          * <dd>A function that, when executed, will remove the nodes
748          * that were inserted</dd>
749          * <dt>
750          * </dl>
751          * </dd>
752          * <dt>scope</dt>
753          * <dd>the execution context for the callbacks</dd>
754          * <dt>win</dt>
755          * <dd>a window other than the one the utility occupies</dd>
756          * <dt>data</dt>
757          * <dd>
758          * data that is supplied to the callbacks when the nodes(s) are
759          * loaded.
760          * </dd>
761          * <dt>insertBefore</dt>
762          * <dd>node or node id that will become the new node's nextSibling</dd>
763          * <dt>charset</dt>
764          * <dd>Node charset, deprecated, use 'attributes'</dd>
765          * <dt>attributes</dt>
766          * <dd>A hash of attributes to apply to dynamic nodes.</dd>
767          * </dl>
768          * <pre>
769          *      YAHOO.util.Get.css("http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css");
770          * </pre>
771          * <pre>
772          *      YAHOO.util.Get.css(["http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css",
773          * </pre>
774          * @return {tId: string} an object containing info about the transaction
775          */
776         css: function(url, opts) {
777             return _queue("css", url, opts);
778         }
779     };
780 }();
781
782 YAHOO.register("get", YAHOO.util.Get, {version: "2.9.0", build: "2800"});