2 * Core MediaWiki JavaScript Library
5 // Attach to window and globally alias
6 window
.mw
= window
.mediaWiki
= new ( function( $ ) {
11 * @var object List of messages that have been requested to be loaded.
13 var messageQueue
= {};
15 /* Object constructors */
20 * Creates an object that can be read from or written to from prototype functions
21 * that allow both single and multiple variables at once.
23 * @param global boolean Whether to store the values in the global window
24 * object or a exclusively in the object property 'values'.
27 function Map( global
) {
28 this.values
= ( global
=== true ) ? window
: {};
34 * Get the value of one or multiple a keys.
36 * If called with no arguments, all values will be returned.
38 * @param selection mixed String key or array of keys to get values for.
39 * @param fallback mixed Value to use in case key(s) do not exist (optional).
40 * @return mixed If selection was a string returns the value or null,
41 * If selection was an array, returns an object of key/values (value is null if not found),
42 * If selection was not passed or invalid, will return the 'values' object member (be careful as
43 * objects are always passed by reference in JavaScript!).
44 * @return Values as a string or object, null if invalid/inexistant.
46 get: function( selection
, fallback
) {
47 if ( $.isArray( selection
) ) {
48 selection
= $.makeArray( selection
);
50 for ( var i
= 0; i
< selection
.length
; i
++ ) {
51 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
54 } else if ( typeof selection
=== 'string' ) {
55 if ( this.values
[selection
] === undefined ) {
56 if ( fallback
!== undefined ) {
61 return this.values
[selection
];
63 if ( selection
=== undefined ) {
66 return null; // invalid selection key
71 * Sets one or multiple key/value pairs.
73 * @param selection mixed String key or array of keys to set values for.
74 * @param value mixed Value to set (optional, only in use when key is a string)
75 * @return bool This returns true on success, false on failure.
77 set: function( selection
, value
) {
78 if ( $.isPlainObject( selection
) ) {
79 for ( var s
in selection
) {
80 this.values
[s
] = selection
[s
];
83 } else if ( typeof selection
=== 'string' && value
!== undefined ) {
84 this.values
[selection
] = value
;
91 * Checks if one or multiple keys exist.
93 * @param selection mixed String key or array of keys to check
94 * @return boolean Existence of key(s)
96 exists: function( selection
) {
97 if ( typeof selection
=== 'object' ) {
98 for ( var s
= 0; s
< selection
.length
; s
++ ) {
99 if ( !( selection
[s
] in this.values
) ) {
105 return selection
in this.values
;
113 * Object constructor for messages,
114 * similar to the Message class in MediaWiki PHP.
116 * @param map Map Instance of mw.Map
118 * @param parameters Array
121 function Message( map
, key
, parameters
) {
122 this.format
= 'parse';
125 this.parameters
= parameters
=== undefined ? [] : $.makeArray( parameters
);
129 Message
.prototype = {
131 * Appends (does not replace) parameters for replacement to the .parameters property.
133 * @param parameters Array
136 params: function( parameters
) {
137 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
138 this.parameters
.push( parameters
[i
] );
144 * Converts message object to it's string form based on the state of format.
146 * @return string Message as a string in the current form or <key> if key does not exist.
148 toString: function() {
149 if ( !this.map
.exists( this.key
) ) {
150 // Return <key> if key does not exist
151 return '<' + this.key
+ '>';
153 var text
= this.map
.get( this.key
),
154 parameters
= this.parameters
;
156 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
157 var index
= parseInt( match
, 10 ) - 1;
158 return index
in parameters
? parameters
[index
] : '$' + match
;
161 if ( this.format
=== 'plain' ) {
164 if ( this.format
=== 'escaped' ) {
165 // According to Message.php this needs {{-transformation, which is
167 return mw
.html
.escape( text
);
170 /* This should be fixed up when we have a parser
171 if ( this.format === 'parse' && 'language' in mw ) {
172 text = mw.language.parse( text );
179 * Changes format to parse and converts message to string
181 * @return {string} String form of parsed message
184 this.format
= 'parse';
185 return this.toString();
189 * Changes format to plain and converts message to string
191 * @return {string} String form of plain message
194 this.format
= 'plain';
195 return this.toString();
199 * Changes the format to html escaped and converts message to string
201 * @return {string} String form of html escaped message
203 escaped: function() {
204 this.format
= 'escaped';
205 return this.toString();
209 * Checks if message exists
211 * @return {string} String form of parsed message
214 return this.map
.exists( this.key
);
221 * Dummy function which in debug mode can be replaced with a function that
222 * emulates console.log in console-less environments.
224 this.log = function() { };
227 * @var constructor Make the Map constructor publicly available.
232 * List of configuration values
234 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
235 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
236 * in the global window object.
243 * Empty object that plugins can be installed in.
248 * Localization system
250 this.messages
= new this.Map();
255 * Gets a message object, similar to wfMessage()
257 * @param key string Key of message to get
258 * @param parameter_1 mixed First argument in a list of variadic arguments,
259 * each a parameter for $N replacement in messages.
262 this.message = function( key
, parameter_1
/* [, parameter_2] */ ) {
264 // Support variadic arguments
265 if ( parameter_1
!== undefined ) {
266 parameters
= $.makeArray( arguments
);
271 return new Message( mw
.messages
, key
, parameters
);
275 * Gets a message string, similar to wfMsg()
277 * @param key string Key of message to get
278 * @param parameters mixed First argument in a list of variadic arguments,
279 * each a parameter for $N replacement in messages.
282 this.msg = function( key
, parameters
) {
283 return mw
.message
.apply( mw
.message
, arguments
).toString();
287 * Client-side module loader which integrates with the MediaWiki ResourceLoader
289 this.loader
= new ( function() {
291 /* Private Members */
294 * Mapping of registered modules
296 * The jquery module is pre-registered, because it must have already
297 * been provided for this object to have been built, and in debug mode
298 * jquery would have been provided through a unique loader request,
299 * making it impossible to hold back registration of jquery until after
305 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
306 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
307 * 'script': function() {},
308 * 'style': 'css code string',
309 * 'messages': { 'key': 'value' },
310 * 'version': ############## (unix timestamp)
314 // List of modules which will be loaded as when ready
316 // List of modules to be loaded
318 // List of callback functions waiting for modules to be ready to be called
320 // Flag inidicating that document ready has occured
322 // Selector cache for the marker element. Use getMarker() to get/use the marker!
325 /* Private Methods */
327 function getMarker(){
332 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
333 if ( $marker
.length
) {
336 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
337 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
342 function compare( a
, b
) {
343 if ( a
.length
!== b
.length
) {
346 for ( var i
= 0; i
< b
.length
; i
++ ) {
347 if ( $.isArray( a
[i
] ) ) {
348 if ( !compare( a
[i
], b
[i
] ) ) {
352 if ( a
[i
] !== b
[i
] ) {
360 * Generates an ISO8601 "basic" string from a UNIX timestamp
362 function formatVersionNumber( timestamp
) {
363 var pad = function( a
, b
, c
) {
364 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
367 d
.setTime( timestamp
* 1000 );
369 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
370 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
375 * Recursively resolves dependencies and detects circular references
377 function recurse( module
, resolved
, unresolved
) {
378 if ( registry
[module
] === undefined ) {
379 throw new Error( 'Unknown dependency: ' + module
);
381 // Resolves dynamic loader function and replaces it with its own results
382 if ( $.isFunction( registry
[module
].dependencies
) ) {
383 registry
[module
].dependencies
= registry
[module
].dependencies();
384 // Ensures the module's dependencies are always in an array
385 if ( typeof registry
[module
].dependencies
!== 'object' ) {
386 registry
[module
].dependencies
= [registry
[module
].dependencies
];
389 // Tracks down dependencies
390 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
391 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
392 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
394 'Circular reference detected: ' + module
+
395 ' -> ' + registry
[module
].dependencies
[n
]
398 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
401 resolved
[resolved
.length
] = module
;
402 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
406 * Gets a list of module names that a module depends on in their proper dependency order
408 * @param module string module name or array of string module names
409 * @return list of dependencies
410 * @throws Error if circular reference is detected
412 function resolve( module
) {
413 // Allow calling with an array of module names
414 if ( typeof module
=== 'object' ) {
416 for ( var m
= 0; m
< module
.length
; m
++ ) {
417 var dependencies
= resolve( module
[m
] );
418 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
419 modules
[modules
.length
] = dependencies
[n
];
423 } else if ( typeof module
=== 'string' ) {
424 // Undefined modules have no dependencies
425 if ( !( module
in registry
) ) {
429 recurse( module
, resolved
, [] );
432 throw new Error( 'Invalid module argument: ' + module
);
436 * Narrows a list of module names down to those matching a specific
437 * state. Possible states are 'undefined', 'registered', 'loading',
438 * 'loaded', or 'ready'
440 * @param states string or array of strings of module states to filter by
441 * @param modules array list of module names to filter (optional, all modules
442 * will be used by default)
443 * @return array list of filtered module names
445 function filter( states
, modules
) {
446 // Allow states to be given as a string
447 if ( typeof states
=== 'string' ) {
450 // If called without a list of modules, build and use a list of all modules
451 var list
= [], module
;
452 if ( modules
=== undefined ) {
454 for ( module
in registry
) {
455 modules
[modules
.length
] = module
;
458 // Build a list of modules which are in one of the specified states
459 for ( var s
= 0; s
< states
.length
; s
++ ) {
460 for ( var m
= 0; m
< modules
.length
; m
++ ) {
461 if ( registry
[modules
[m
]] === undefined ) {
462 // Module does not exist
463 if ( states
[s
] === 'undefined' ) {
465 list
[list
.length
] = modules
[m
];
468 // Module exists, check state
469 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
471 list
[list
.length
] = modules
[m
];
480 * Executes a loaded module, making it ready to use
482 * @param module string module name to execute
484 function execute( module
, callback
) {
485 if ( registry
[module
] === undefined ) {
486 throw new Error( 'Module has not been registered yet: ' + module
);
487 } else if ( registry
[module
].state
=== 'registered' ) {
488 throw new Error( 'Module has not been requested from the server yet: ' + module
);
489 } else if ( registry
[module
].state
=== 'loading' ) {
490 throw new Error( 'Module has not completed loading yet: ' + module
);
491 } else if ( registry
[module
].state
=== 'ready' ) {
492 throw new Error( 'Module has already been loaded: ' + module
);
496 if ( $.isPlainObject( registry
[module
].style
) ) {
497 for ( var media
in registry
[module
].style
) {
498 style
= registry
[module
].style
[media
];
499 if ( $.isArray( style
) ) {
500 for ( var i
= 0; i
< style
.length
; i
++ ) {
501 getMarker().before( mw
.html
.element( 'link', {
507 } else if ( typeof style
=== 'string' ) {
508 getMarker().before( mw
.html
.element( 'style', {
511 }, new mw
.html
.Cdata( style
) ) );
515 // Add localizations to message system
516 if ( $.isPlainObject( registry
[module
].messages
) ) {
517 mw
.messages
.set( registry
[module
].messages
);
521 var script
= registry
[module
].script
,
522 markModuleReady = function() {
523 registry
[module
].state
= 'ready';
524 handlePending( module
);
525 if ( $.isFunction( callback
) ) {
530 if ( $.isArray( script
) ) {
532 if ( script
.length
=== 0 ) {
533 // No scripts in this module? Let's dive out early.
536 for ( var i
= 0; i
< script
.length
; i
++ ) {
537 registry
[module
].state
= 'loading';
538 addScript( script
[i
], function() {
539 if ( ++done
=== script
.length
) {
544 } else if ( $.isFunction( script
) ) {
549 // This needs to NOT use mw.log because these errors are common in production mode
550 // and not in debug mode, such as when a symbol that should be global isn't exported
551 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
552 console
.log( 'mw.loader::execute> Exception thrown by ' + module
+ ': ' + e
.message
);
554 registry
[module
].state
= 'error';
560 * Automatically executes jobs and modules which are pending with satistifed dependencies.
562 * This is used when dependencies are satisfied, such as when a module is executed.
564 function handlePending( module
) {
566 // Run jobs who's dependencies have just been met
567 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
569 filter( 'ready', jobs
[j
].dependencies
),
570 jobs
[j
].dependencies
) )
572 if ( $.isFunction( jobs
[j
].ready
) ) {
579 // Execute modules who's dependencies have just been met
580 for ( var r
in registry
) {
581 if ( registry
[r
].state
=== 'loaded' ) {
583 filter( ['ready'], registry
[r
].dependencies
),
584 registry
[r
].dependencies
) )
591 // Run error callbacks of jobs affected by this condition
592 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
593 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
594 if ( $.isFunction( jobs
[j
].error
) ) {
605 * Adds a dependencies to the queue with optional callbacks to be run
606 * when the dependencies are ready or fail
608 * @param dependencies string module name or array of string module names
609 * @param ready function callback to execute when all dependencies are ready
610 * @param error function callback to execute when any dependency fails
612 function request( dependencies
, ready
, error
) {
613 // Allow calling by single module name
614 if ( typeof dependencies
=== 'string' ) {
615 dependencies
= [dependencies
];
616 if ( dependencies
[0] in registry
) {
617 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
618 dependencies
[dependencies
.length
] = registry
[dependencies
[0]].dependencies
[n
];
622 // Add ready and error callbacks if they were given
623 if ( arguments
.length
> 1 ) {
624 jobs
[jobs
.length
] = {
625 'dependencies': filter(
626 ['undefined', 'registered', 'loading', 'loaded'],
633 // Queue up any dependencies that are undefined or registered
634 dependencies
= filter( ['undefined', 'registered'], dependencies
);
635 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
636 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
637 queue
[queue
.length
] = dependencies
[n
];
644 function sortQuery(o
) {
645 var sorted
= {}, key
, a
= [];
647 if ( o
.hasOwnProperty( key
) ) {
652 for ( key
= 0; key
< a
.length
; key
++ ) {
653 sorted
[a
[key
]] = o
[a
[key
]];
659 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
660 * to a query string of the form foo.bar,baz|bar.baz,quux
662 function buildModulesString( moduleMap
) {
664 for ( var prefix
in moduleMap
) {
665 p
= prefix
=== '' ? '' : prefix
+ '.';
666 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
668 return arr
.join( '|' );
672 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
673 * depending on whether document-ready has occured yet.
675 * @param src String: URL to script, will be used as the src attribute in the script tag
676 * @param callback Function: Optional callback which will be run when the script is done
678 function addScript( src
, callback
) {
679 var done
= false, script
;
681 // jQuery's getScript method is NOT better than doing this the old-fassioned way
682 // because jQuery will eval the script's code, and errors will not have sane
684 script
= document
.createElement( 'script' );
685 script
.setAttribute( 'src', src
);
686 script
.setAttribute( 'type', 'text/javascript' );
687 if ( $.isFunction( callback
) ) {
688 // Attach handlers for all browsers -- this is based on jQuery.ajax
689 script
.onload
= script
.onreadystatechange = function() {
695 || /loaded|complete/.test( script
.readyState
)
701 // Handle memory leak in IE
702 script
.onload
= script
.onreadystatechange
= null;
706 if ( script
.parentNode
) {
707 script
.parentNode
.removeChild( script
);
710 // Dereference the script
715 document
.body
.appendChild( script
);
717 document
.write( mw
.html
.element(
718 'script', { 'type': 'text/javascript', 'src': src
}, ''
720 if ( $.isFunction( callback
) ) {
721 // Document.write is synchronous, so this is called when it's done
730 * Requests dependencies from server, loading and executing when things when ready.
732 this.work = function() {
733 // Build a list of request parameters
735 'skin': mw
.config
.get( 'skin' ),
736 'lang': mw
.config
.get( 'wgUserLanguage' ),
737 'debug': mw
.config
.get( 'debug' )
739 // Extend request parameters with a list of modules in the batch
744 // Appends a list of modules to the batch
745 for ( var q
= 0; q
< queue
.length
; q
++ ) {
746 // Only request modules which are undefined or registered
747 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
=== 'registered' ) {
748 // Prevent duplicate entries
749 if ( $.inArray( queue
[q
], batch
) === -1 ) {
750 batch
[batch
.length
] = queue
[q
];
751 // Mark registered modules as loading
752 if ( queue
[q
] in registry
) {
753 registry
[queue
[q
]].state
= 'loading';
758 // Early exit if there's nothing to load
759 if ( !batch
.length
) {
762 // Clean up the queue
764 // Always order modules alphabetically to help reduce cache
765 // misses for otherwise identical content
767 for ( var b
= 0; b
< batch
.length
; b
++ ) {
768 var bGroup
= registry
[batch
[b
]].group
;
769 if ( !( bGroup
in groups
) ) {
772 groups
[bGroup
][groups
[bGroup
].length
] = batch
[b
];
774 for ( var group
in groups
) {
775 // Calculate the highest timestamp
777 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
778 if ( registry
[groups
[group
][g
]].version
> version
) {
779 version
= registry
[groups
[group
][g
]].version
;
783 var reqBase
= $.extend( { 'version': formatVersionNumber( version
) }, base
),
784 reqBaseLength
= $.param( reqBase
).length
,
786 limit
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 ),
787 // We may need to split up the request to honor the query string length limit,
788 // so build it piece by piece.
789 l
= reqBaseLength
+ 9, // '&modules='.length == 9
792 reqs
[0] = {}; // { prefix: [ suffixes ] }
794 for ( var i
= 0; i
< groups
[group
].length
; i
++ ) {
795 // Determine how many bytes this module would add to the query string
796 var lastDotIndex
= groups
[group
][i
].lastIndexOf( '.' ),
797 // Note that these substr() calls work even if lastDotIndex == -1
798 prefix
= groups
[group
][i
].substr( 0, lastDotIndex
),
799 suffix
= groups
[group
][i
].substr( lastDotIndex
+ 1 ),
800 bytesAdded
= prefix
in reqs
[r
]
801 ? suffix
.length
+ 3 // '%2C'.length == 3
802 : groups
[group
][i
].length
+ 3; // '%7C'.length == 3
804 // If the request would become too long, create a new one,
805 // but don't create empty requests
806 if ( limit
> 0 && !$.isEmptyObject( reqs
[r
] ) && l
+ bytesAdded
> limit
) {
807 // This request would become too long, create a new one
810 l
= reqBaseLength
+ 9;
812 if ( !( prefix
in reqs
[r
] ) ) {
813 reqs
[r
][prefix
] = [];
815 reqs
[r
][prefix
].push( suffix
);
818 for ( var r
= 0; r
< reqs
.length
; r
++ ) {
819 requests
[requests
.length
] = $.extend(
820 { 'modules': buildModulesString( reqs
[r
] ) }, reqBase
824 // Clear the batch - this MUST happen before we append the
825 // script element to the body or it's possible that the script
826 // will be locally cached, instantly load, and work the batch
827 // again, all before we've cleared it causing each request to
828 // include modules which are already loaded
830 // Asynchronously append a script tag to the end of the body
831 for ( var r
= 0; r
< requests
.length
; r
++ ) {
832 requests
[r
] = sortQuery( requests
[r
] );
833 // Append &* to avoid triggering the IE6 extension check
834 var src
= mw
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] ) + '&*';
840 * Registers a module, letting the system know about it and its
841 * dependencies. loader.js files contain calls to this function.
843 this.register = function( module
, version
, dependencies
, group
) {
844 // Allow multiple registration
845 if ( typeof module
=== 'object' ) {
846 for ( var m
= 0; m
< module
.length
; m
++ ) {
847 if ( typeof module
[m
] === 'string' ) {
848 mw
.loader
.register( module
[m
] );
849 } else if ( typeof module
[m
] === 'object' ) {
850 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
856 if ( typeof module
!== 'string' ) {
857 throw new Error( 'module must be a string, not a ' + typeof module
);
859 if ( registry
[module
] !== undefined ) {
860 throw new Error( 'module already implemented: ' + module
);
862 // List the module as registered
864 'state': 'registered',
865 'group': typeof group
=== 'string' ? group
: null,
867 'version': version
!== undefined ? parseInt( version
, 10 ) : 0
869 if ( typeof dependencies
=== 'string' ) {
870 // Allow dependencies to be given as a single module name
871 registry
[module
].dependencies
= [dependencies
];
872 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
873 // Allow dependencies to be given as an array of module names
874 // or a function which returns an array
875 registry
[module
].dependencies
= dependencies
;
880 * Implements a module, giving the system a course of action to take
881 * upon loading. Results of a request for one or more modules contain
882 * calls to this function.
884 * All arguments are required.
886 * @param module String: Name of module
887 * @param script Mixed: Function of module code or String of URL to be used as the src
888 * attribute when adding a script element to the body
889 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
890 * keyed by media-type
891 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
893 this.implement = function( module
, script
, style
, msgs
) {
895 if ( typeof module
!== 'string' ) {
896 throw new Error( 'module must be a string, not a ' + typeof module
);
898 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
899 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
901 if ( !$.isPlainObject( style
) ) {
902 throw new Error( 'style must be an object, not a ' + typeof style
);
904 if ( !$.isPlainObject( msgs
) ) {
905 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
907 // Automatically register module
908 if ( registry
[module
] === undefined ) {
909 mw
.loader
.register( module
);
911 // Check for duplicate implementation
912 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
913 throw new Error( 'module already implemeneted: ' + module
);
915 // Mark module as loaded
916 registry
[module
].state
= 'loaded';
918 registry
[module
].script
= script
;
919 registry
[module
].style
= style
;
920 registry
[module
].messages
= msgs
;
921 // Execute or queue callback
923 filter( ['ready'], registry
[module
].dependencies
),
924 registry
[module
].dependencies
) )
933 * Executes a function as soon as one or more required modules are ready
935 * @param dependencies string or array of strings of modules names the callback
936 * dependencies to be ready before executing
937 * @param ready function callback to execute when all dependencies are ready (optional)
938 * @param error function callback to execute when if dependencies have a errors (optional)
940 this.using = function( dependencies
, ready
, error
) {
941 var tod
= typeof dependencies
;
943 if ( tod
!== 'object' && tod
!== 'string' ) {
944 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
946 // Allow calling with a single dependency as a string
947 if ( tod
=== 'string' ) {
948 dependencies
= [dependencies
];
950 // Resolve entire dependency map
951 dependencies
= resolve( dependencies
);
952 // If all dependencies are met, execute ready immediately
953 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
954 if ( $.isFunction( ready
) ) {
958 // If any dependencies have errors execute error immediately
959 else if ( filter( ['error'], dependencies
).length
) {
960 if ( $.isFunction( error
) ) {
964 // Since some dependencies are not yet ready, queue up a request
966 request( dependencies
, ready
, error
);
971 * Loads an external script or one or more modules for future use
973 * @param modules mixed either the name of a module, array of modules,
974 * or a URL of an external script or style
975 * @param type string mime-type to use if calling with a URL of an
976 * external script or style; acceptable values are "text/css" and
977 * "text/javascript"; if no type is provided, text/javascript is assumed.
979 this.load = function( modules
, type
) {
981 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
982 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
984 // Allow calling with an external script or single dependency as a string
985 if ( typeof modules
=== 'string' ) {
986 // Support adding arbitrary external scripts
987 if ( modules
.substr( 0, 7 ) === 'http://' || modules
.substr( 0, 8 ) === 'https://' ) {
988 if ( type
=== 'text/css' ) {
989 $( 'head' ).append( $( '<link/>', {
995 } else if ( type
=== 'text/javascript' || type
=== undefined ) {
996 addScript( modules
);
1002 // Called with single module
1003 modules
= [modules
];
1005 // Resolve entire dependency map
1006 modules
= resolve( modules
);
1007 // If all modules are ready, nothing dependency be done
1008 if ( compare( filter( ['ready'], modules
), modules
) ) {
1011 // If any modules have errors return false
1012 else if ( filter( ['error'], modules
).length
) {
1015 // Since some modules are not yet ready, queue up a request
1023 * Changes the state of a module
1025 * @param module string module name or object of module name/state pairs
1026 * @param state string state name
1028 this.state = function( module
, state
) {
1029 if ( typeof module
=== 'object' ) {
1030 for ( var m
in module
) {
1031 mw
.loader
.state( m
, module
[m
] );
1035 if ( !( module
in registry
) ) {
1036 mw
.loader
.register( module
);
1038 registry
[module
].state
= state
;
1042 * Gets the version of a module
1044 * @param module string name of module to get version for
1046 this.getVersion = function( module
) {
1047 if ( module
in registry
&& 'version' in registry
[module
] ) {
1048 return formatVersionNumber( registry
[module
].version
);
1054 * @deprecated use mw.loader.getVersion() instead
1056 this.version = function() {
1057 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1061 * Gets the state of a module
1063 * @param module string name of module to get state for
1065 this.getState = function( module
) {
1066 if ( module
in registry
&& 'state' in registry
[module
] ) {
1067 return registry
[module
].state
;
1072 /* Cache document ready status */
1074 $(document
).ready( function() { ready
= true; } );
1077 /** HTML construction helper functions */
1078 this.html
= new ( function () {
1079 var escapeCallback = function( s
) {
1095 * Escape a string for HTML. Converts special characters to HTML entities.
1096 * @param s The string to escape
1098 this.escape = function( s
) {
1099 return s
.replace( /['"<>&]/g, escapeCallback
);
1103 * Wrapper object for raw HTML passed to mw.html.element().
1105 this.Raw = function( value
) {
1110 * Wrapper object for CDATA element contents passed to mw.html.element()
1112 this.Cdata = function( value
) {
1117 * Create an HTML element string, with safe escaping.
1119 * @param name The tag name.
1120 * @param attrs An object with members mapping element names to values
1121 * @param contents The contents of the element. May be either:
1122 * - string: The string is escaped.
1123 * - null or undefined: The short closing form is used, e.g. <br/>.
1124 * - this.Raw: The value attribute is included without escaping.
1125 * - this.Cdata: The value attribute is included, and an exception is
1126 * thrown if it contains an illegal ETAGO delimiter.
1127 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1131 * return h.element( 'div', {},
1132 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1133 * Returns <div><img src="<"/></div>
1135 this.element = function( name
, attrs
, contents
) {
1137 for ( var attrName
in attrs
) {
1138 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1140 if ( contents
=== undefined || contents
=== null ) {
1147 if ( typeof contents
=== 'string' ) {
1149 s
+= this.escape( contents
);
1150 } else if ( contents
instanceof this.Raw
) {
1151 // Raw HTML inclusion
1152 s
+= contents
.value
;
1153 } else if ( contents
instanceof this.Cdata
) {
1155 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1156 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1158 s
+= contents
.value
;
1160 throw new Error( 'mw.html.element: Invalid type of contents' );
1162 s
+= '</' + name
+ '>';
1167 /* Extension points */
1173 // Alias $j to jQuery for backwards compatibility
1176 // Auto-register from pre-loaded startup scripts
1177 if ( jQuery
.isFunction( startUp
) ) {