Landing some minor perf optimization to jQuery().
[jquery.git] / src / core.js
1 // Define a local copy of jQuery
2 var jQuery = function( selector, context ) {
3                 // The jQuery object is actually just the init constructor 'enhanced'
4                 return new jQuery.fn.init( selector, context );
5         },
6
7         // Map over jQuery in case of overwrite
8         _jQuery = window.jQuery,
9
10         // Map over the $ in case of overwrite
11         _$ = window.$,
12
13         // Use the correct document accordingly with window argument (sandbox)
14         document = window.document,
15
16         // A central reference to the root jQuery(document)
17         rootjQuery,
18
19         // A simple way to check for HTML strings or ID strings
20         // (both of which we optimize for)
21         quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,
22
23         // Is it a simple selector
24         isSimple = /^.[^:#\[\.,]*$/,
25
26         // Check if a string has a non-whitespace character in it
27         rnotwhite = /\S/,
28
29         // Used for trimming whitespace
30         rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,
31
32         // Match a standalone tag
33         rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
34
35         // Keep a UserAgent string for use with jQuery.browser
36         userAgent = navigator.userAgent,
37
38         // For matching the engine and version of the browser
39         browserMatch,
40         
41         // Has the ready events already been bound?
42         readyBound = false,
43         
44         // The functions to execute on DOM ready
45         readyList = [],
46
47         // The ready event handler
48         DOMContentLoaded,
49
50         // Save a reference to some core methods
51         toString = Object.prototype.toString,
52         hasOwnProperty = Object.prototype.hasOwnProperty,
53         push = Array.prototype.push,
54         slice = Array.prototype.slice,
55         indexOf = Array.prototype.indexOf;
56
57 jQuery.fn = jQuery.prototype = {
58         init: function( selector, context ) {
59                 var match, elem, ret, doc;
60
61                 // Handle $(""), $(null), or $(undefined)
62                 if ( !selector ) {
63                         return this;
64                 }
65
66                 // Handle $(DOMElement)
67                 if ( selector.nodeType ) {
68                         this.context = this[0] = selector;
69                         this.length = 1;
70                         return this;
71                 }
72                 
73                 // The body element only exists once, optimize finding it
74                 if ( selector === "body" && !context ) {
75                         this.context = this[0] = document.body;
76                         this.selector = "body";
77                         this.length = 1;
78                         return this;
79                 }
80
81                 // Handle HTML strings
82                 if ( typeof selector === "string" ) {
83                         // Are we dealing with HTML string or an ID?
84                         match = quickExpr.exec( selector );
85
86                         // Verify a match, and that no context was specified for #id
87                         if ( match && (match[1] || !context) ) {
88
89                                 // HANDLE: $(html) -> $(array)
90                                 if ( match[1] ) {
91                                         doc = (context ? context.ownerDocument || context : document);
92
93                                         // If a single string is passed in and it's a single tag
94                                         // just do a createElement and skip the rest
95                                         ret = rsingleTag.exec( selector );
96
97                                         if ( ret ) {
98                                                 if ( jQuery.isPlainObject( context ) ) {
99                                                         selector = [ document.createElement( ret[1] ) ];
100                                                         jQuery.fn.attr.call( selector, context, true );
101
102                                                 } else {
103                                                         selector = [ doc.createElement( ret[1] ) ];
104                                                 }
105
106                                         } else {
107                                                 ret = buildFragment( [ match[1] ], [ doc ] );
108                                                 selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
109                                         }
110                                         
111                                         return jQuery.merge( this, selector );
112                                         
113                                 // HANDLE: $("#id")
114                                 } else {
115                                         elem = document.getElementById( match[2] );
116
117                                         if ( elem ) {
118                                                 // Handle the case where IE and Opera return items
119                                                 // by name instead of ID
120                                                 if ( elem.id !== match[2] ) {
121                                                         return rootjQuery.find( selector );
122                                                 }
123
124                                                 // Otherwise, we inject the element directly into the jQuery object
125                                                 this.length = 1;
126                                                 this[0] = elem;
127                                         }
128
129                                         this.context = document;
130                                         this.selector = selector;
131                                         return this;
132                                 }
133
134                         // HANDLE: $("TAG")
135                         } else if ( !context && /^\w+$/.test( selector ) ) {
136                                 this.selector = selector;
137                                 this.context = document;
138                                 selector = document.getElementsByTagName( selector );
139                                 return jQuery.merge( this, selector );
140
141                         // HANDLE: $(expr, $(...))
142                         } else if ( !context || context.jquery ) {
143                                 return (context || rootjQuery).find( selector );
144
145                         // HANDLE: $(expr, context)
146                         // (which is just equivalent to: $(context).find(expr)
147                         } else {
148                                 return jQuery( context ).find( selector );
149                         }
150
151                 // HANDLE: $(function)
152                 // Shortcut for document ready
153                 } else if ( jQuery.isFunction( selector ) ) {
154                         return rootjQuery.ready( selector );
155                 }
156
157                 if (selector.selector !== undefined) {
158                         this.selector = selector.selector;
159                         this.context = selector.context;
160                 }
161
162                 return jQuery.makeArray( selector, this );
163         },
164
165         // Start with an empty selector
166         selector: "",
167
168         // The current version of jQuery being used
169         jquery: "@VERSION",
170
171         // The default length of a jQuery object is 0
172         length: 0,
173
174         // The number of elements contained in the matched element set
175         size: function() {
176                 return this.length;
177         },
178
179         toArray: function() {
180                 return slice.call( this, 0 );
181         },
182
183         // Get the Nth element in the matched element set OR
184         // Get the whole matched element set as a clean array
185         get: function( num ) {
186                 return num == null ?
187
188                         // Return a 'clean' array
189                         this.toArray() :
190
191                         // Return just the object
192                         ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
193         },
194
195         // Take an array of elements and push it onto the stack
196         // (returning the new matched element set)
197         pushStack: function( elems, name, selector ) {
198                 // Build a new jQuery matched element set
199                 var ret = jQuery( elems || null );
200
201                 // Add the old object onto the stack (as a reference)
202                 ret.prevObject = this;
203
204                 ret.context = this.context;
205
206                 if ( name === "find" ) {
207                         ret.selector = this.selector + (this.selector ? " " : "") + selector;
208                 } else if ( name ) {
209                         ret.selector = this.selector + "." + name + "(" + selector + ")";
210                 }
211
212                 // Return the newly-formed element set
213                 return ret;
214         },
215
216         // Force the current matched set of elements to become
217         // the specified array of elements (destroying the stack in the process)
218         // You should use pushStack() in order to do this, but maintain the stack
219         setArray: function( elems ) {
220                 // Resetting the length to 0, then using the native Array push
221                 // is a super-fast way to populate an object with array-like properties
222                 this.length = 0;
223                 push.apply( this, elems );
224
225                 return this;
226         },
227
228         // Execute a callback for every element in the matched set.
229         // (You can seed the arguments with an array of args, but this is
230         // only used internally.)
231         each: function( callback, args ) {
232                 return jQuery.each( this, callback, args );
233         },
234         
235         ready: function( fn ) {
236                 // Attach the listeners
237                 jQuery.bindReady();
238
239                 // If the DOM is already ready
240                 if ( jQuery.isReady ) {
241                         // Execute the function immediately
242                         fn.call( document, jQuery );
243
244                 // Otherwise, remember the function for later
245                 } else if ( readyList ) {
246                         // Add the function to the wait list
247                         readyList.push( fn );
248                 }
249
250                 return this;
251         },
252         
253         eq: function( i ) {
254                 return i === -1 ?
255                         this.slice( i ) :
256                         this.slice( i, +i + 1 );
257         },
258
259         first: function() {
260                 return this.eq( 0 );
261         },
262
263         last: function() {
264                 return this.eq( -1 );
265         },
266
267         slice: function() {
268                 return this.pushStack( slice.apply( this, arguments ),
269                         "slice", slice.call(arguments).join(",") );
270         },
271
272         map: function( callback ) {
273                 return this.pushStack( jQuery.map(this, function( elem, i ) {
274                         return callback.call( elem, i, elem );
275                 }));
276         },
277         
278         end: function() {
279                 return this.prevObject || jQuery(null);
280         },
281
282         // For internal use only.
283         // Behaves like an Array's method, not like a jQuery method.
284         push: push,
285         sort: [].sort,
286         splice: [].splice
287 };
288
289 // Give the init function the jQuery prototype for later instantiation
290 jQuery.fn.init.prototype = jQuery.fn;
291
292 jQuery.extend = jQuery.fn.extend = function() {
293         // copy reference to target object
294         var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
295
296         // Handle a deep copy situation
297         if ( typeof target === "boolean" ) {
298                 deep = target;
299                 target = arguments[1] || {};
300                 // skip the boolean and the target
301                 i = 2;
302         }
303
304         // Handle case when target is a string or something (possible in deep copy)
305         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
306                 target = {};
307         }
308
309         // extend jQuery itself if only one argument is passed
310         if ( length === i ) {
311                 target = this;
312                 --i;
313         }
314
315         for ( ; i < length; i++ ) {
316                 // Only deal with non-null/undefined values
317                 if ( (options = arguments[ i ]) != null ) {
318                         // Extend the base object
319                         for ( name in options ) {
320                                 src = target[ name ];
321                                 copy = options[ name ];
322
323                                 // Prevent never-ending loop
324                                 if ( target === copy ) {
325                                         continue;
326                                 }
327
328                                 // Recurse if we're merging object literal values or arrays
329                                 if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) {
330                                         var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src
331                                                 : jQuery.isArray(copy) ? [] : {};
332
333                                         // Never move original objects, clone them
334                                         target[ name ] = jQuery.extend( deep, clone, copy );
335
336                                 // Don't bring in undefined values
337                                 } else if ( copy !== undefined ) {
338                                         target[ name ] = copy;
339                                 }
340                         }
341                 }
342         }
343
344         // Return the modified object
345         return target;
346 };
347
348 jQuery.extend({
349         noConflict: function( deep ) {
350                 window.$ = _$;
351
352                 if ( deep ) {
353                         window.jQuery = _jQuery;
354                 }
355
356                 return jQuery;
357         },
358         
359         // Is the DOM ready to be used? Set to true once it occurs.
360         isReady: false,
361         
362         // Handle when the DOM is ready
363         ready: function() {
364                 // Make sure that the DOM is not already loaded
365                 if ( !jQuery.isReady ) {
366                         // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
367                         if ( !document.body ) {
368                                 return setTimeout( jQuery.ready, 13 );
369                         }
370
371                         // Remember that the DOM is ready
372                         jQuery.isReady = true;
373
374                         // If there are functions bound, to execute
375                         if ( readyList ) {
376                                 // Execute all of them
377                                 var fn, i = 0;
378                                 while ( (fn = readyList[ i++ ]) ) {
379                                         fn.call( document, jQuery );
380                                 }
381
382                                 // Reset the list of functions
383                                 readyList = null;
384                         }
385
386                         // Trigger any bound ready events
387                         if ( jQuery.fn.triggerHandler ) {
388                                 jQuery( document ).triggerHandler( "ready" );
389                         }
390                 }
391         },
392         
393         bindReady: function() {
394                 if ( readyBound ) {
395                         return;
396                 }
397
398                 readyBound = true;
399
400                 // Catch cases where $(document).ready() is called after the
401                 // browser event has already occurred.
402                 if ( document.readyState === "complete" ) {
403                         return jQuery.ready();
404                 }
405
406                 // Mozilla, Opera and webkit nightlies currently support this event
407                 if ( document.addEventListener ) {
408                         // Use the handy event callback
409                         document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
410                         
411                         // A fallback to window.onload, that will always work
412                         window.addEventListener( "load", jQuery.ready, false );
413
414                 // If IE event model is used
415                 } else if ( document.attachEvent ) {
416                         // ensure firing before onload,
417                         // maybe late but safe also for iframes
418                         document.attachEvent("onreadystatechange", DOMContentLoaded);
419                         
420                         // A fallback to window.onload, that will always work
421                         window.attachEvent( "onload", jQuery.ready );
422
423                         // If IE and not a frame
424                         // continually check to see if the document is ready
425                         var toplevel = false;
426
427                         try {
428                                 toplevel = window.frameElement == null;
429                         } catch(e) {}
430
431                         if ( document.documentElement.doScroll && toplevel ) {
432                                 doScrollCheck();
433                         }
434                 }
435         },
436
437         // See test/unit/core.js for details concerning isFunction.
438         // Since version 1.3, DOM methods and functions like alert
439         // aren't supported. They return false on IE (#2968).
440         isFunction: function( obj ) {
441                 return toString.call(obj) === "[object Function]";
442         },
443
444         isArray: function( obj ) {
445                 return toString.call(obj) === "[object Array]";
446         },
447
448         isPlainObject: function( obj ) {
449                 // Must be an Object.
450                 // Because of IE, we also have to check the presence of the constructor property.
451                 // Make sure that DOM nodes and window objects don't pass through, as well
452                 if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) {
453                         return false;
454                 }
455                 
456                 // Not own constructor property must be Object
457                 if ( obj.constructor
458                         && !hasOwnProperty.call(obj, "constructor")
459                         && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
460                         return false;
461                 }
462                 
463                 // Own properties are enumerated firstly, so to speed up,
464                 // if last one is own, then all properties are own.
465         
466                 var key;
467                 for ( key in obj ) {}
468                 
469                 return key === undefined || hasOwnProperty.call( obj, key );
470         },
471
472         isEmptyObject: function( obj ) {
473                 for ( var name in obj ) {
474                         return false;
475                 }
476                 return true;
477         },
478         
479         error: function( msg ) {
480                 throw msg;
481         },
482         
483         parseJSON: function( data ) {
484                 if ( typeof data !== "string" || !data ) {
485                         return null;
486                 }
487                 
488                 // Make sure the incoming data is actual JSON
489                 // Logic borrowed from http://json.org/json2.js
490                 if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
491                         .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
492                         .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
493
494                         // Try to use the native JSON parser first
495                         return window.JSON && window.JSON.parse ?
496                                 window.JSON.parse( data ) :
497                                 (new Function("return " + data))();
498
499                 } else {
500                         jQuery.error( "Invalid JSON: " + data );
501                 }
502         },
503
504         noop: function() {},
505
506         // Evalulates a script in a global context
507         globalEval: function( data ) {
508                 if ( data && rnotwhite.test(data) ) {
509                         // Inspired by code by Andrea Giammarchi
510                         // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
511                         var head = document.getElementsByTagName("head")[0] || document.documentElement,
512                                 script = document.createElement("script");
513
514                         script.type = "text/javascript";
515
516                         if ( jQuery.support.scriptEval ) {
517                                 script.appendChild( document.createTextNode( data ) );
518                         } else {
519                                 script.text = data;
520                         }
521
522                         // Use insertBefore instead of appendChild to circumvent an IE6 bug.
523                         // This arises when a base node is used (#2709).
524                         head.insertBefore( script, head.firstChild );
525                         head.removeChild( script );
526                 }
527         },
528
529         nodeName: function( elem, name ) {
530                 return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
531         },
532
533         // args is for internal usage only
534         each: function( object, callback, args ) {
535                 var name, i = 0,
536                         length = object.length,
537                         isObj = length === undefined || jQuery.isFunction(object);
538
539                 if ( args ) {
540                         if ( isObj ) {
541                                 for ( name in object ) {
542                                         if ( callback.apply( object[ name ], args ) === false ) {
543                                                 break;
544                                         }
545                                 }
546                         } else {
547                                 for ( ; i < length; ) {
548                                         if ( callback.apply( object[ i++ ], args ) === false ) {
549                                                 break;
550                                         }
551                                 }
552                         }
553
554                 // A special, fast, case for the most common use of each
555                 } else {
556                         if ( isObj ) {
557                                 for ( name in object ) {
558                                         if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
559                                                 break;
560                                         }
561                                 }
562                         } else {
563                                 for ( var value = object[0];
564                                         i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
565                         }
566                 }
567
568                 return object;
569         },
570
571         trim: function( text ) {
572                 return (text || "").replace( rtrim, "" );
573         },
574
575         // results is for internal usage only
576         makeArray: function( array, results ) {
577                 var ret = results || [];
578
579                 if ( array != null ) {
580                         // The window, strings (and functions) also have 'length'
581                         // The extra typeof function check is to prevent crashes
582                         // in Safari 2 (See: #3039)
583                         if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) {
584                                 push.call( ret, array );
585                         } else {
586                                 jQuery.merge( ret, array );
587                         }
588                 }
589
590                 return ret;
591         },
592
593         inArray: function( elem, array ) {
594                 if ( array.indexOf ) {
595                         return array.indexOf( elem );
596                 }
597
598                 for ( var i = 0, length = array.length; i < length; i++ ) {
599                         if ( array[ i ] === elem ) {
600                                 return i;
601                         }
602                 }
603
604                 return -1;
605         },
606
607         merge: function( first, second ) {
608                 var i = first.length, j = 0;
609
610                 if ( typeof second.length === "number" ) {
611                         for ( var l = second.length; j < l; j++ ) {
612                                 first[ i++ ] = second[ j ];
613                         }
614                 
615                 } else {
616                         while ( second[j] !== undefined ) {
617                                 first[ i++ ] = second[ j++ ];
618                         }
619                 }
620
621                 first.length = i;
622
623                 return first;
624         },
625
626         grep: function( elems, callback, inv ) {
627                 var ret = [];
628
629                 // Go through the array, only saving the items
630                 // that pass the validator function
631                 for ( var i = 0, length = elems.length; i < length; i++ ) {
632                         if ( !inv !== !callback( elems[ i ], i ) ) {
633                                 ret.push( elems[ i ] );
634                         }
635                 }
636
637                 return ret;
638         },
639
640         // arg is for internal usage only
641         map: function( elems, callback, arg ) {
642                 var ret = [], value;
643
644                 // Go through the array, translating each of the items to their
645                 // new value (or values).
646                 for ( var i = 0, length = elems.length; i < length; i++ ) {
647                         value = callback( elems[ i ], i, arg );
648
649                         if ( value != null ) {
650                                 ret[ ret.length ] = value;
651                         }
652                 }
653
654                 return ret.concat.apply( [], ret );
655         },
656
657         // A global GUID counter for objects
658         guid: 1,
659
660         proxy: function( fn, proxy, thisObject ) {
661                 if ( arguments.length === 2 ) {
662                         if ( typeof proxy === "string" ) {
663                                 thisObject = fn;
664                                 fn = thisObject[ proxy ];
665                                 proxy = undefined;
666
667                         } else if ( proxy && !jQuery.isFunction( proxy ) ) {
668                                 thisObject = proxy;
669                                 proxy = undefined;
670                         }
671                 }
672
673                 if ( !proxy && fn ) {
674                         proxy = function() {
675                                 return fn.apply( thisObject || this, arguments );
676                         };
677                 }
678
679                 // Set the guid of unique handler to the same of original handler, so it can be removed
680                 if ( fn ) {
681                         proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
682                 }
683
684                 // So proxy can be declared as an argument
685                 return proxy;
686         },
687
688         // Use of jQuery.browser is frowned upon.
689         // More details: http://docs.jquery.com/Utilities/jQuery.browser
690         uaMatch: function( ua ) {
691                 ua = ua.toLowerCase();
692
693                 var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
694                         /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) ||
695                         /(msie) ([\w.]+)/.exec( ua ) ||
696                         !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) ||
697                         [];
698
699                 return { browser: match[1] || "", version: match[2] || "0" };
700         },
701
702         browser: {}
703 });
704
705 browserMatch = jQuery.uaMatch( userAgent );
706 if ( browserMatch.browser ) {
707         jQuery.browser[ browserMatch.browser ] = true;
708         jQuery.browser.version = browserMatch.version;
709 }
710
711 // Deprecated, use jQuery.browser.webkit instead
712 if ( jQuery.browser.webkit ) {
713         jQuery.browser.safari = true;
714 }
715
716 if ( indexOf ) {
717         jQuery.inArray = function( elem, array ) {
718                 return indexOf.call( array, elem );
719         };
720 }
721
722 // All jQuery objects should point back to these
723 rootjQuery = jQuery(document);
724
725 // Cleanup functions for the document ready method
726 if ( document.addEventListener ) {
727         DOMContentLoaded = function() {
728                 document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
729                 jQuery.ready();
730         };
731
732 } else if ( document.attachEvent ) {
733         DOMContentLoaded = function() {
734                 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
735                 if ( document.readyState === "complete" ) {
736                         document.detachEvent( "onreadystatechange", DOMContentLoaded );
737                         jQuery.ready();
738                 }
739         };
740 }
741
742 // The DOM ready check for Internet Explorer
743 function doScrollCheck() {
744         if ( jQuery.isReady ) {
745                 return;
746         }
747
748         try {
749                 // If IE is used, use the trick by Diego Perini
750                 // http://javascript.nwbox.com/IEContentLoaded/
751                 document.documentElement.doScroll("left");
752         } catch( error ) {
753                 setTimeout( doScrollCheck, 1 );
754                 return;
755         }
756
757         // and execute any waiting functions
758         jQuery.ready();
759 }
760
761 function evalScript( i, elem ) {
762         if ( elem.src ) {
763                 jQuery.ajax({
764                         url: elem.src,
765                         async: false,
766                         dataType: "script"
767                 });
768         } else {
769                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
770         }
771
772         if ( elem.parentNode ) {
773                 elem.parentNode.removeChild( elem );
774         }
775 }
776
777 // Mutifunctional method to get and set values to a collection
778 // The value/s can be optionally by executed if its a function
779 function access( elems, key, value, exec, fn, pass ) {
780         var length = elems.length;
781         
782         // Setting many attributes
783         if ( typeof key === "object" ) {
784                 for ( var k in key ) {
785                         access( elems, k, key[k], exec, fn, value );
786                 }
787                 return elems;
788         }
789         
790         // Setting one attribute
791         if ( value !== undefined ) {
792                 // Optionally, function values get executed if exec is true
793                 exec = !pass && exec && jQuery.isFunction(value);
794                 
795                 for ( var i = 0; i < length; i++ ) {
796                         fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
797                 }
798                 
799                 return elems;
800         }
801         
802         // Getting an attribute
803         return length ? fn( elems[0], key ) : null;
804 }
805
806 function now() {
807         return (new Date).getTime();
808 }