]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/yui/build/get/get.js
Release 6.2.0beta4
[Github/sugarcrm.git] / include / javascript / yui / build / get / get.js
1 /*
2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
5 version: 2.8.0r4
6 */
7 /**
8  * Provides a mechanism to fetch remote resources and
9  * insert them into a document
10  * @module get
11  * @requires yahoo
12  */
13
14 /**
15  * Fetches and inserts one or more script or link nodes into the document 
16  * @namespace YAHOO.util
17  * @class YAHOO.util.Get
18  */
19 YAHOO.util.Get = function() {
20
21     /**
22      * hash of queues to manage multiple requests
23      * @property queues
24      * @private
25      */
26     var queues={}, 
27         
28     /**
29      * queue index used to generate transaction ids
30      * @property qidx
31      * @type int
32      * @private
33      */
34         qidx=0, 
35         
36     /**
37      * node index used to generate unique node ids
38      * @property nidx
39      * @type int
40      * @private
41      */
42         nidx=0, 
43
44         // ridx=0,
45
46         // sandboxFrame=null,
47
48     /**
49      * interal property used to prevent multiple simultaneous purge 
50      * processes
51      * @property purging
52      * @type boolean
53      * @private
54      */
55         purging=false,
56
57         ua=YAHOO.env.ua, 
58         
59         lang=YAHOO.lang;
60     
61     /** 
62      * Generates an HTML element, this is not appended to a document
63      * @method _node
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
68      * @private
69      */
70     var _node = function(type, attr, win) {
71         var w = win || window, d=w.document, n=d.createElement(type);
72
73         for (var i in attr) {
74             if (attr[i] && YAHOO.lang.hasOwnProperty(attr, i)) {
75                 n.setAttribute(i, attr[i]);
76             }
77         }
78
79         return n;
80     };
81
82     /**
83      * Generates a link node
84      * @method _linkNode
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
88      * @private
89      */
90     var _linkNode = function(url, win, attributes) {
91
92         var o = {
93             id:   "yui__dyn_" + (nidx++),
94             type: "text/css",
95             rel:  "stylesheet",
96             href: url
97         };
98
99         if (attributes) {
100             lang.augmentObject(o, attributes);
101         }
102
103         return _node("link", o, win);
104     };
105
106     /**
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
112      * @private
113      */
114     var _scriptNode = function(url, win, attributes) {
115         var o = {
116             id:   "yui__dyn_" + (nidx++),
117             type: "text/javascript",
118             src:  url
119         };
120
121         if (attributes) {
122             lang.augmentObject(o, attributes);
123         }
124
125         return _node("script", o, win);
126     };
127
128     /**
129      * Returns the data payload for callback functions
130      * @method _returnData
131      * @private
132      */
133     var _returnData = function(q, msg) {
134         return {
135                 tId: q.tId,
136                 win: q.win,
137                 data: q.data,
138                 nodes: q.nodes,
139                 msg: msg,
140                 purge: function() {
141                     _purge(this.tId);
142                 }
143             };
144     };
145
146     var _get = function(nId, tId) {
147         var q = queues[tId],
148             n = (lang.isString(nId)) ? q.win.document.getElementById(nId) : nId;
149         if (!n) {
150             _fail(tId, "target node not found: " + nId);
151         }
152
153         return n;
154     };
155
156     /*
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
160      * @method _fail
161      * @param id {string} the id of the request
162      * @private
163      */
164     var _fail = function(id, msg) {
165         var q = queues[id];
166         // execute failure callback
167         if (q.onFailure) {
168             var sc=q.scope || q.win;
169             q.onFailure.call(sc, _returnData(q, msg));
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     var _finish = function(id) {
180         var q = queues[id];
181         q.finished = true;
182
183         if (q.aborted) {
184             var msg = "transaction " + id + " was aborted";
185             _fail(id, msg);
186             return;
187         }
188
189         // execute success callback
190         if (q.onSuccess) {
191             var sc=q.scope || q.win;
192             q.onSuccess.call(sc, _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     var _timeout = function(id) {
203         var q = queues[id];
204         if (q.onTimeout) {
205             var sc=q.scope || q;
206             q.onTimeout.call(sc, _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     var _next = function(id, loaded) {
218         var q = queues[id];
219
220         if (q.timer) {
221             // Y.log('cancel timer');
222             q.timer.cancel();
223         }
224
225         if (q.aborted) {
226             var msg = "transaction " + id + " was aborted";
227             _fail(id, msg);
228             return;
229         }
230
231         if (loaded) {
232             q.url.shift(); 
233             if (q.varName) {
234                 q.varName.shift(); 
235             }
236         } else {
237             // This is the first pass: make sure the url is an array
238             q.url = (lang.isString(q.url)) ? [q.url] : q.url;
239             if (q.varName) {
240                 q.varName = (lang.isString(q.varName)) ? [q.varName] : q.varName;
241             }
242         }
243
244         var w=q.win, d=w.document, h=d.getElementsByTagName("head")[0], n;
245
246         if (q.url.length === 0) {
247             // Safari 2.x workaround - There is no way to know when 
248             // a script is ready in versions of Safari prior to 3.x.
249             // Adding an extra node reduces the problem, but doesn't
250             // eliminate it completely because the browser executes
251             // them asynchronously. 
252             if (q.type === "script" && ua.webkit && ua.webkit < 420 && 
253                     !q.finalpass && !q.varName) {
254                 // Add another script node.  This does not guarantee that the
255                 // scripts will execute in order, but it does appear to fix the
256                 // problem on fast connections more effectively than using an
257                 // arbitrary timeout.  It is possible that the browser does
258                 // block subsequent script execution in this case for a limited
259                 // time.
260                 var extra = _scriptNode(null, q.win, q.attributes);
261                 extra.innerHTML='YAHOO.util.Get._finalize("' + id + '");';
262                 q.nodes.push(extra); h.appendChild(extra);
263
264             } else {
265                 _finish(id);
266             }
267
268             return;
269         } 
270
271
272         var url = q.url[0];
273
274         // if the url is undefined, this is probably a trailing comma problem in IE
275         if (!url) {
276             q.url.shift(); 
277             return _next(id);
278         }
279
280
281         if (q.timeout) {
282             // Y.log('create timer');
283             q.timer = lang.later(q.timeout, q, _timeout, id);
284         }
285
286         if (q.type === "script") {
287             n = _scriptNode(url, w, q.attributes);
288         } else {
289             n = _linkNode(url, w, q.attributes);
290         }
291
292         // track this node's load progress
293         _track(q.type, n, id, url, w, q.url.length);
294
295         // add the node to the queue so we can return it to the user supplied callback
296         q.nodes.push(n);
297
298         // add it to the head or insert it before 'insertBefore'
299         if (q.insertBefore) {
300             var s = _get(q.insertBefore, id);
301             if (s) {
302                 s.parentNode.insertBefore(n, s);
303             }
304         } else {
305             h.appendChild(n);
306         }
307         
308
309         // FireFox does not support the onload event for link nodes, so there is
310         // no way to make the css requests synchronous. This means that the css 
311         // rules in multiple files could be applied out of order in this browser
312         // if a later request returns before an earlier one.  Safari too.
313         if ((ua.webkit || ua.gecko) && q.type === "css") {
314             _next(id, url);
315         }
316     };
317
318     /**
319      * Removes processed queues and corresponding nodes
320      * @method _autoPurge
321      * @private
322      */
323     var _autoPurge = function() {
324
325         if (purging) {
326             return;
327         }
328
329         purging = true;
330         for (var i in queues) {
331             var q = queues[i];
332             if (q.autopurge && q.finished) {
333                 _purge(q.tId);
334                 delete queues[i];
335             }
336         }
337
338         purging = false;
339     };
340
341     /**
342      * Removes the nodes for the specified queue
343      * @method _purge
344      * @private
345      */
346     var _purge = function(tId) {
347         if (queues[tId]) {
348
349             var q     = queues[tId],
350                 nodes = q.nodes, 
351                 l     = nodes.length, 
352                 d     = q.win.document, 
353                 h     = d.getElementsByTagName("head")[0],
354                 sib, i, node, attr;
355
356             if (q.insertBefore) {
357                 sib = _get(q.insertBefore, tId);
358                 if (sib) {
359                     h = sib.parentNode;
360                 }
361             }
362
363             for (i=0; i<l; i=i+1) {
364                 node = nodes[i];
365                 if (node.clearAttributes) {
366                     node.clearAttributes();
367                 } else {
368                     for (attr in node) {
369                         delete node[attr];
370                     }
371                 }
372
373                 h.removeChild(node);
374             }
375
376             q.nodes = [];
377         }
378     };
379
380     /**
381      * Saves the state for the request and begins loading
382      * the requested urls
383      * @method queue
384      * @param type {string} the type of node to insert
385      * @param url {string} the url to load
386      * @param opts the hash of options for this request
387      * @private
388      */
389     var _queue = function(type, url, opts) {
390
391         var id = "q" + (qidx++);
392         opts = opts || {};
393
394         if (qidx % YAHOO.util.Get.PURGE_THRESH === 0) {
395             _autoPurge();
396         }
397
398         queues[id] = lang.merge(opts, {
399             tId: id,
400             type: type,
401             url: url,
402             finished: false,
403             aborted: false,
404             nodes: []
405         });
406
407         var q = queues[id];
408         q.win = q.win || window;
409         q.scope = q.scope || q.win;
410         q.autopurge = ("autopurge" in q) ? q.autopurge : 
411                       (type === "script") ? true : false;
412
413         if (opts.charset) {
414             q.attributes = q.attributes || {};
415             q.attributes.charset = opts.charset;
416         }
417
418         lang.later(0, q, _next, id);
419
420         return {
421             tId: id
422         };
423     };
424
425     /**
426      * Detects when a node has been loaded.  In the case of
427      * script nodes, this does not guarantee that contained
428      * script is ready to use.
429      * @method _track
430      * @param type {string} the type of node to track
431      * @param n {HTMLElement} the node to track
432      * @param id {string} the id of the request
433      * @param url {string} the url that is being loaded
434      * @param win {Window} the targeted window
435      * @param qlength the number of remaining items in the queue,
436      * including this one
437      * @param trackfn {Function} function to execute when finished
438      * the default is _next
439      * @private
440      */
441     var _track = function(type, n, id, url, win, qlength, trackfn) {
442         var f = trackfn || _next;
443
444         // IE supports the readystatechange event for script and css nodes
445         if (ua.ie) {
446             n.onreadystatechange = function() {
447                 var rs = this.readyState;
448                 if ("loaded" === rs || "complete" === rs) {
449                     n.onreadystatechange = null;
450                     f(id, url);
451                 }
452             };
453
454         // webkit prior to 3.x is problemmatic
455         } else if (ua.webkit) {
456
457             if (type === "script") {
458
459                 // Safari 3.x supports the load event for script nodes (DOM2)
460                 if (ua.webkit >= 420) {
461
462                     n.addEventListener("load", function() {
463                         f(id, url);
464                     });
465
466                 // Nothing can be done with Safari < 3.x except to pause and hope
467                 // for the best, particularly after last script is inserted. The
468                 // scripts will always execute in the order they arrive, not
469                 // necessarily the order in which they were inserted.  To support
470                 // script nodes with complete reliability in these browsers, script
471                 // nodes either need to invoke a function in the window once they
472                 // are loaded or the implementer needs to provide a well-known
473                 // property that the utility can poll for.
474                 } else {
475                     // Poll for the existence of the named variable, if it
476                     // was supplied.
477                     var q = queues[id];
478                     if (q.varName) {
479                         var freq=YAHOO.util.Get.POLL_FREQ;
480                         q.maxattempts = YAHOO.util.Get.TIMEOUT/freq;
481                         q.attempts = 0;
482                         q._cache = q.varName[0].split(".");
483                         q.timer = lang.later(freq, q, function(o) {
484                             var a=this._cache, l=a.length, w=this.win, i;
485                             for (i=0; i<l; i=i+1) {
486                                 w = w[a[i]];
487                                 if (!w) {
488                                     // if we have exausted our attempts, give up
489                                     this.attempts++;
490                                     if (this.attempts++ > this.maxattempts) {
491                                         var msg = "Over retry limit, giving up";
492                                         q.timer.cancel();
493                                         _fail(id, msg);
494                                     } else {
495                                     }
496                                     return;
497                                 }
498                             }
499                             
500
501                             q.timer.cancel();
502                             f(id, url);
503
504                         }, null, true);
505                     } else {
506                         lang.later(YAHOO.util.Get.POLL_FREQ, null, f, [id, url]);
507                     }
508                 }
509             } 
510
511         // FireFox and Opera support onload (but not DOM2 in FF) handlers for
512         // script nodes.  Opera, but not FF, supports the onload event for link
513         // nodes.
514         } else { 
515             n.onload = function() {
516                 f(id, url);
517             };
518         }
519     };
520
521     return {
522
523         /**
524          * The default poll freqency in ms, when needed
525          * @property POLL_FREQ
526          * @static
527          * @type int
528          * @default 10
529          */
530         POLL_FREQ: 10,
531
532         /**
533          * The number of request required before an automatic purge.
534          * property PURGE_THRESH
535          * @static
536          * @type int
537          * @default 20
538          */
539         PURGE_THRESH: 20,
540
541         /**
542          * The length time to poll for varName when loading a script in
543          * Safari 2.x before the transaction fails.
544          * property TIMEOUT
545          * @static
546          * @type int
547          * @default 2000
548          */
549         TIMEOUT: 2000,
550         
551         /**
552          * Called by the the helper for detecting script load in Safari
553          * @method _finalize
554          * @param id {string} the transaction id
555          * @private
556          */
557         _finalize: function(id) {
558             lang.later(0, null, _finish, id);
559         },
560
561         /**
562          * Abort a transaction
563          * @method abort
564          * @param {string|object} either the tId or the object returned from
565          * script() or css()
566          */
567         abort: function(o) {
568             var id = (lang.isString(o)) ? o : o.tId;
569             var q = queues[id];
570             if (q) {
571                 q.aborted = true;
572             }
573         }, 
574
575         /**
576          * Fetches and inserts one or more script nodes into the head
577          * of the current document or the document in a specified window.
578          *
579          * @method script
580          * @static
581          * @param url {string|string[]} the url or urls to the script(s)
582          * @param opts {object} Options: 
583          * <dl>
584          * <dt>onSuccess</dt>
585          * <dd>
586          * callback to execute when the script(s) are finished loading
587          * The callback receives an object back with the following
588          * data:
589          * <dl>
590          * <dt>win</dt>
591          * <dd>the window the script(s) were inserted into</dd>
592          * <dt>data</dt>
593          * <dd>the data object passed in when the request was made</dd>
594          * <dt>nodes</dt>
595          * <dd>An array containing references to the nodes that were
596          * inserted</dd>
597          * <dt>purge</dt>
598          * <dd>A function that, when executed, will remove the nodes
599          * that were inserted</dd>
600          * <dt>
601          * </dl>
602          * </dd>
603          * <dt>onFailure</dt>
604          * <dd>
605          * callback to execute when the script load operation fails
606          * The callback receives an object back with the following
607          * data:
608          * <dl>
609          * <dt>win</dt>
610          * <dd>the window the script(s) were inserted into</dd>
611          * <dt>data</dt>
612          * <dd>the data object passed in when the request was made</dd>
613          * <dt>nodes</dt>
614          * <dd>An array containing references to the nodes that were
615          * inserted successfully</dd>
616          * <dt>purge</dt>
617          * <dd>A function that, when executed, will remove any nodes
618          * that were inserted</dd>
619          * <dt>
620          * </dl>
621          * </dd>
622          * <dt>onTimeout</dt>
623          * <dd>
624          * callback to execute when a timeout occurs.
625          * The callback receives an object back with the following
626          * data:
627          * <dl>
628          * <dt>win</dt>
629          * <dd>the window the script(s) were inserted into</dd>
630          * <dt>data</dt>
631          * <dd>the data object passed in when the request was made</dd>
632          * <dt>nodes</dt>
633          * <dd>An array containing references to the nodes that were
634          * inserted</dd>
635          * <dt>purge</dt>
636          * <dd>A function that, when executed, will remove the nodes
637          * that were inserted</dd>
638          * <dt>
639          * </dl>
640          * </dd>
641          * <dt>scope</dt>
642          * <dd>the execution context for the callbacks</dd>
643          * <dt>win</dt>
644          * <dd>a window other than the one the utility occupies</dd>
645          * <dt>autopurge</dt>
646          * <dd>
647          * setting to true will let the utilities cleanup routine purge 
648          * the script once loaded
649          * </dd>
650          * <dt>data</dt>
651          * <dd>
652          * data that is supplied to the callback when the script(s) are
653          * loaded.
654          * </dd>
655          * <dt>varName</dt>
656          * <dd>
657          * variable that should be available when a script is finished
658          * loading.  Used to help Safari 2.x and below with script load 
659          * detection.  The type of this property should match what was
660          * passed into the url parameter: if loading a single url, a
661          * string can be supplied.  If loading multiple scripts, you
662          * must supply an array that contains the variable name for
663          * each script.
664          * </dd>
665          * <dt>insertBefore</dt>
666          * <dd>node or node id that will become the new node's nextSibling</dd>
667          * </dl>
668          * <dt>charset</dt>
669          * <dd>Node charset, deprecated, use 'attributes'</dd>
670          * <dt>attributes</dt>
671          * <dd>A hash of attributes to apply to dynamic nodes.</dd>
672          * <dt>timeout</dt>
673          * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd>
674          * <pre>
675          * // assumes yahoo, dom, and event are already on the page
676          * &nbsp;&nbsp;YAHOO.util.Get.script(
677          * &nbsp;&nbsp;["http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js",
678          * &nbsp;&nbsp;&nbsp;"http://yui.yahooapis.com/2.7.0/build/animation/animation-min.js"], &#123;
679          * &nbsp;&nbsp;&nbsp;&nbsp;onSuccess: function(o) &#123;
680          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new YAHOO.util.DDProxy("dd1"); // also new o.reference("dd1"); would work
681          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.log("won't cause error because YAHOO is the scope");
682          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.log(o.nodes.length === 2) // true
683          * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// o.purge(); // optionally remove the script nodes immediately
684          * &nbsp;&nbsp;&nbsp;&nbsp;&#125;,
685          * &nbsp;&nbsp;&nbsp;&nbsp;onFailure: function(o) &#123;
686          * &nbsp;&nbsp;&nbsp;&nbsp;&#125;,
687          * &nbsp;&nbsp;&nbsp;&nbsp;data: "foo",
688          * &nbsp;&nbsp;&nbsp;&nbsp;timeout: 10000, // 10 second timeout
689          * &nbsp;&nbsp;&nbsp;&nbsp;scope: YAHOO,
690          * &nbsp;&nbsp;&nbsp;&nbsp;// win: otherframe // target another window/frame
691          * &nbsp;&nbsp;&nbsp;&nbsp;autopurge: true // allow the utility to choose when to remove the nodes
692          * &nbsp;&nbsp;&#125;);
693          * </pre>
694          * @return {tId: string} an object containing info about the transaction
695          */
696         script: function(url, opts) { return _queue("script", url, opts); },
697
698         /**
699          * Fetches and inserts one or more css link nodes into the 
700          * head of the current document or the document in a specified
701          * window.
702          * @method css
703          * @static
704          * @param url {string} the url or urls to the css file(s)
705          * @param opts Options: 
706          * <dl>
707          * <dt>onSuccess</dt>
708          * <dd>
709          * callback to execute when the css file(s) are finished loading
710          * The callback receives an object back with the following
711          * data:
712          * <dl>win</dl>
713          * <dd>the window the link nodes(s) were inserted into</dd>
714          * <dt>data</dt>
715          * <dd>the data object passed in when the request was made</dd>
716          * <dt>nodes</dt>
717          * <dd>An array containing references to the nodes that were
718          * inserted</dd>
719          * <dt>purge</dt>
720          * <dd>A function that, when executed, will remove the nodes
721          * that were inserted</dd>
722          * <dt>
723          * </dl>
724          * </dd>
725          * <dt>scope</dt>
726          * <dd>the execution context for the callbacks</dd>
727          * <dt>win</dt>
728          * <dd>a window other than the one the utility occupies</dd>
729          * <dt>data</dt>
730          * <dd>
731          * data that is supplied to the callbacks when the nodes(s) are
732          * loaded.
733          * </dd>
734          * <dt>insertBefore</dt>
735          * <dd>node or node id that will become the new node's nextSibling</dd>
736          * <dt>charset</dt>
737          * <dd>Node charset, deprecated, use 'attributes'</dd>
738          * <dt>attributes</dt>
739          * <dd>A hash of attributes to apply to dynamic nodes.</dd>
740          * </dl>
741          * <pre>
742          *      YAHOO.util.Get.css("http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css");
743          * </pre>
744          * <pre>
745          *      YAHOO.util.Get.css(["http://yui.yahooapis.com/2.7.0/build/menu/assets/skins/sam/menu.css",
746          * </pre>
747          * @return {tId: string} an object containing info about the transaction
748          */
749         css: function(url, opts) {
750             return _queue("css", url, opts); 
751         }
752     };
753 }();
754
755 YAHOO.register("get", YAHOO.util.Get, {version: "2.8.0r4", build: "2449"});