2 * Core MediaWiki JavaScript Library
6 window
.mediaWiki
= new ( function( $ ) {
12 // List of messages that have been requested to be loaded
13 var messageQueue
= {};
18 * An object which allows single and multiple get/set/exists functionality
19 * on a list of key / value pairs.
21 * @param {boolean} global Whether to get/set/exists values on the window
22 * object or a private object
24 function Map( global
) {
25 this.values
= ( global
=== true ) ? window
: {};
29 * Gets the value of a key, or a list of key/value pairs for an array of keys.
31 * If called with no arguments, all values will be returned.
33 * @param selection mixed Key or array of keys to get values for
34 * @param fallback mixed Value to use in case key(s) do not exist (optional)
36 Map
.prototype.get = function( selection
, fallback
) {
37 if ( typeof selection
=== 'object' ) {
38 selection
= $.makeArray( selection
);
40 for ( var i
= 0; i
< selection
.length
; i
++ ) {
41 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
44 } else if ( typeof selection
=== 'string' ) {
45 if ( typeof this.values
[selection
] === 'undefined' ) {
46 if ( typeof fallback
!== 'undefined' ) {
51 return this.values
[selection
];
57 * Sets one or multiple key/value pairs.
59 * @param selection mixed Key or object of key/value pairs to set
60 * @param value mixed Value to set (optional, only in use when key is a string)
62 Map
.prototype.set = function( selection
, value
) {
63 if ( typeof selection
=== 'object' ) {
64 for ( var s
in selection
) {
65 this.values
[s
] = selection
[s
];
68 } else if ( typeof selection
=== 'string' && typeof value
!== 'undefined' ) {
69 this.values
[selection
] = value
;
76 * Checks if one or multiple keys exist.
78 * @param selection mixed Key or array of keys to check
79 * @return boolean Existence of key(s)
81 Map
.prototype.exists = function( selection
) {
82 if ( typeof selection
=== 'object' ) {
83 for ( var s
= 0; s
< selection
.length
; s
++ ) {
84 if ( !( selection
[s
] in this.values
) ) {
90 return selection
in this.values
;
95 * Message object, similar to Message in PHP
97 function Message( map
, key
, parameters
) {
98 this.format
= 'parse';
101 this.parameters
= typeof parameters
=== 'undefined' ? [] : $.makeArray( parameters
);
105 * Appends parameters for replacement
107 * @param parameters mixed First in a list of variadic arguments to append as message parameters
109 Message
.prototype.params = function( parameters
) {
110 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
111 this.parameters
[this.parameters
.length
] = parameters
[i
];
117 * Converts message object to it's string form based on the state of format
119 * @return {string} String form of message
121 Message
.prototype.toString = function() {
122 if ( !this.map
.exists( this.key
) ) {
123 // Return <key> if key does not exist
124 return '<' + this.key
+ '>';
126 var text
= this.map
.get( this.key
);
127 var parameters
= this.parameters
;
128 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
129 var index
= parseInt( match
, 10 ) - 1;
130 return index
in parameters
? parameters
[index
] : '$' + match
;
133 if ( this.format
=== 'plain' ) {
136 if ( this.format
=== 'escaped' ) {
137 // According to Message.php this needs {{-transformation, which is
139 return mw
.html
.escape( text
);
142 /* This should be fixed up when we have a parser
143 if ( this.format === 'parse' && 'language' in mediaWiki ) {
144 text = mw.language.parse( text );
151 * Changes format to parse and converts message to string
153 * @return {string} String form of parsed message
155 Message
.prototype.parse = function() {
156 this.format
= 'parse';
157 return this.toString();
161 * Changes format to plain and converts message to string
163 * @return {string} String form of plain message
165 Message
.prototype.plain = function() {
166 this.format
= 'plain';
167 return this.toString();
171 * Changes the format to html escaped and converts message to string
173 * @return {string} String form of html escaped message
175 Message
.prototype.escaped = function() {
176 this.format
= 'escaped';
177 return this.toString();
181 * Checks if message exists
183 * @return {string} String form of parsed message
185 Message
.prototype.exists = function() {
186 return this.map
.exists( this.key
);
192 * Dummy function which in debug mode can be replaced with a function that
193 * does something clever
195 this.log = function() { };
198 * Make the Map-class publicly available
203 * List of configuration values
205 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
206 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
207 * in the global window object.
212 * Localization system
214 this.messages
= new this.Map();
219 * Gets a message object, similar to wfMessage()
221 * @param key string Key of message to get
222 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
225 this.message = function( key
, parameters
) {
226 // Support variadic arguments
227 if ( typeof parameters
!== 'undefined' ) {
228 parameters
= $.makeArray( arguments
);
233 return new Message( mw
.messages
, key
, parameters
);
237 * Gets a message string, similar to wfMsg()
239 * @param key string Key of message to get
240 * @param parameters mixed First argument in a list of variadic arguments, each a parameter for $
243 this.msg = function( key
, parameters
) {
244 return mw
.message
.apply( mw
.message
, arguments
).toString();
248 * Client-side module loader which integrates with the MediaWiki ResourceLoader
250 this.loader
= new ( function() {
252 /* Private Members */
255 * Mapping of registered modules
257 * The jquery module is pre-registered, because it must have already
258 * been provided for this object to have been built, and in debug mode
259 * jquery would have been provided through a unique loader request,
260 * making it impossible to hold back registration of jquery until after
266 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
267 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
268 * 'script': function() {},
269 * 'style': 'css code string',
270 * 'messages': { 'key': 'value' },
271 * 'version': ############## (unix timestamp)
276 // List of modules which will be loaded as when ready
278 // List of modules to be loaded
280 // List of callback functions waiting for modules to be ready to be called
282 // Flag inidicating that document ready has occured
284 // Selector cache for the marker element. Use getMarker() to get/use the marker!
287 /* Private Methods */
289 function getMarker(){
294 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
295 if ( $marker
.length
) {
298 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
299 return $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
303 function compare( a
, b
) {
304 if ( a
.length
!= b
.length
) {
307 for ( var i
= 0; i
< b
.length
; i
++ ) {
308 if ( $.isArray( a
[i
] ) ) {
309 if ( !compare( a
[i
], b
[i
] ) ) {
313 if ( a
[i
] !== b
[i
] ) {
321 * Generates an ISO8601 "basic" string from a UNIX timestamp
323 function formatVersionNumber( timestamp
) {
324 function pad( a
, b
, c
) {
325 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
328 d
.setTime( timestamp
* 1000 );
330 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
331 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
336 * Recursively resolves dependencies and detects circular references
338 function recurse( module
, resolved
, unresolved
) {
339 if ( typeof registry
[module
] === 'undefined' ) {
340 throw new Error( 'Unknown dependency: ' + module
);
342 // Resolves dynamic loader function and replaces it with its own results
343 if ( $.isFunction( registry
[module
].dependencies
) ) {
344 registry
[module
].dependencies
= registry
[module
].dependencies();
345 // Ensures the module's dependencies are always in an array
346 if ( typeof registry
[module
].dependencies
!== 'object' ) {
347 registry
[module
].dependencies
= [registry
[module
].dependencies
];
350 // Tracks down dependencies
351 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
352 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
353 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
355 'Circular reference detected: ' + module
+
356 ' -> ' + registry
[module
].dependencies
[n
]
359 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
362 resolved
[resolved
.length
] = module
;
363 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
367 * Gets a list of module names that a module depends on in their proper dependency order
369 * @param module string module name or array of string module names
370 * @return list of dependencies
371 * @throws Error if circular reference is detected
373 function resolve( module
) {
374 // Allow calling with an array of module names
375 if ( typeof module
=== 'object' ) {
377 for ( var m
= 0; m
< module
.length
; m
++ ) {
378 var dependencies
= resolve( module
[m
] );
379 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
380 modules
[modules
.length
] = dependencies
[n
];
384 } else if ( typeof module
=== 'string' ) {
385 // Undefined modules have no dependencies
386 if ( !( module
in registry
) ) {
390 recurse( module
, resolved
, [] );
393 throw new Error( 'Invalid module argument: ' + module
);
397 * Narrows a list of module names down to those matching a specific
398 * state. Possible states are 'undefined', 'registered', 'loading',
399 * 'loaded', or 'ready'
401 * @param states string or array of strings of module states to filter by
402 * @param modules array list of module names to filter (optional, all modules
403 * will be used by default)
404 * @return array list of filtered module names
406 function filter( states
, modules
) {
407 // Allow states to be given as a string
408 if ( typeof states
=== 'string' ) {
411 // If called without a list of modules, build and use a list of all modules
412 var list
= [], module
;
413 if ( typeof modules
=== 'undefined' ) {
415 for ( module
in registry
) {
416 modules
[modules
.length
] = module
;
419 // Build a list of modules which are in one of the specified states
420 for ( var s
= 0; s
< states
.length
; s
++ ) {
421 for ( var m
= 0; m
< modules
.length
; m
++ ) {
422 if ( typeof registry
[modules
[m
]] === 'undefined' ) {
423 // Module does not exist
424 if ( states
[s
] == 'undefined' ) {
426 list
[list
.length
] = modules
[m
];
429 // Module exists, check state
430 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
432 list
[list
.length
] = modules
[m
];
441 * Executes a loaded module, making it ready to use
443 * @param module string module name to execute
445 function execute( module
, callback
) {
446 var _fn
= 'mw.loader::execute> ';
447 if ( typeof registry
[module
] === 'undefined' ) {
448 throw new Error( 'Module has not been registered yet: ' + module
);
449 } else if ( registry
[module
].state
=== 'registered' ) {
450 throw new Error( 'Module has not been requested from the server yet: ' + module
);
451 } else if ( registry
[module
].state
=== 'loading' ) {
452 throw new Error( 'Module has not completed loading yet: ' + module
);
453 } else if ( registry
[module
].state
=== 'ready' ) {
454 throw new Error( 'Module has already been loaded: ' + module
);
457 if ( $.isPlainObject( registry
[module
].style
) ) {
458 for ( var media
in registry
[module
].style
) {
459 var style
= registry
[module
].style
[media
];
460 if ( $.isArray( style
) ) {
461 for ( var i
= 0; i
< style
.length
; i
++ ) {
462 getMarker().before( mw
.html
.element( 'link', {
468 } else if ( typeof style
=== 'string' ) {
469 getMarker().before( mw
.html
.element(
471 { 'type': 'text/css', 'media': media
},
472 new mw
.html
.Cdata( style
)
477 // Add localizations to message system
478 if ( $.isPlainObject( registry
[module
].messages
) ) {
479 mw
.messages
.set( registry
[module
].messages
);
483 var script
= registry
[module
].script
;
484 var markModuleReady = function() {
485 registry
[module
].state
= 'ready';
486 handlePending( module
);
487 if ( $.isFunction( callback
) ) {
491 if ( $.isArray( script
) ) {
493 if (script
.length
== 0 ) {
494 // No scripts in this module? Let's dive out early.
497 for ( var i
= 0; i
< script
.length
; i
++ ) {
498 registry
[module
].state
= 'loading';
499 addScript( script
[i
], function() {
500 if ( ++done
== script
.length
) {
505 } else if ( $.isFunction( script
) ) {
510 // This needs to NOT use mw.log because these errors are common in production mode
511 // and not in debug mode, such as when a symbol that should be global isn't exported
512 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
513 console
.log( _fn
+ 'Exception thrown by ' + module
+ ': ' + e
.message
);
516 registry
[module
].state
= 'error';
521 * Automatically executes jobs and modules which are pending with satistifed dependencies.
523 * This is used when dependencies are satisfied, such as when a module is executed.
525 function handlePending( module
) {
527 // Run jobs who's dependencies have just been met
528 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
530 filter( 'ready', jobs
[j
].dependencies
),
531 jobs
[j
].dependencies
) )
533 if ( $.isFunction( jobs
[j
].ready
) ) {
540 // Execute modules who's dependencies have just been met
541 for ( var r
in registry
) {
542 if ( registry
[r
].state
== 'loaded' ) {
544 filter( ['ready'], registry
[r
].dependencies
),
545 registry
[r
].dependencies
) )
552 // Run error callbacks of jobs affected by this condition
553 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
554 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
555 if ( $.isFunction( jobs
[j
].error
) ) {
566 * Adds a dependencies to the queue with optional callbacks to be run
567 * when the dependencies are ready or fail
569 * @param dependencies string module name or array of string module names
570 * @param ready function callback to execute when all dependencies are ready
571 * @param error function callback to execute when any dependency fails
573 function request( dependencies
, ready
, error
) {
574 // Allow calling by single module name
575 if ( typeof dependencies
=== 'string' ) {
576 dependencies
= [dependencies
];
577 if ( dependencies
[0] in registry
) {
578 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
579 dependencies
[dependencies
.length
] =
580 registry
[dependencies
[0]].dependencies
[n
];
584 // Add ready and error callbacks if they were given
585 if ( arguments
.length
> 1 ) {
586 jobs
[jobs
.length
] = {
587 'dependencies': filter(
588 ['undefined', 'registered', 'loading', 'loaded'],
594 // Queue up any dependencies that are undefined or registered
595 dependencies
= filter( ['undefined', 'registered'], dependencies
);
596 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
597 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
598 queue
[queue
.length
] = dependencies
[n
];
605 function sortQuery(o
) {
606 var sorted
= {}, key
, a
= [];
608 if ( o
.hasOwnProperty( key
) ) {
613 for ( key
= 0; key
< a
.length
; key
++ ) {
614 sorted
[a
[key
]] = o
[a
[key
]];
620 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
621 * to a query string of the form foo.bar,baz|bar.baz,quux
623 function buildModulesString( moduleMap
) {
625 for ( var prefix
in moduleMap
) {
626 var p
= prefix
=== '' ? '' : prefix
+ '.';
627 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
629 return arr
.join( '|' ).replace( /\./g, '!' );
633 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
634 * depending on whether document-ready has occured yet.
636 * @param src String: URL to script, will be used as the src attribute in the script tag
637 * @param callback Function: Optional callback which will be run when the script is done
639 function addScript( src
, callback
) {
641 // jQuery's getScript method is NOT better than doing this the old-fassioned way
642 // because jQuery will eval the script's code, and errors will not have sane
644 var script
= document
.createElement( 'script' );
645 script
.setAttribute( 'src', src
);
646 script
.setAttribute( 'type', 'text/javascript' );
647 if ( $.isFunction( callback
) ) {
649 // Attach handlers for all browsers -- this is based on jQuery.getScript
650 script
.onload
= script
.onreadystatechange = function() {
655 || this.readyState
=== "loaded"
656 || this.readyState
=== "complete"
661 // Handle memory leak in IE
662 script
.onload
= script
.onreadystatechange
= null;
663 if ( script
.parentNode
) {
664 script
.parentNode
.removeChild( script
);
669 document
.body
.appendChild( script
);
671 document
.write( mw
.html
.element(
672 'script', { 'type': 'text/javascript', 'src': src
}, ''
674 if ( $.isFunction( callback
) ) {
675 // Document.write is synchronous, so this is called when it's done
684 * Requests dependencies from server, loading and executing when things when ready.
686 this.work = function() {
687 // Appends a list of modules to the batch
688 for ( var q
= 0; q
< queue
.length
; q
++ ) {
689 // Only request modules which are undefined or registered
690 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
691 // Prevent duplicate entries
692 if ( $.inArray( queue
[q
], batch
) === -1 ) {
693 batch
[batch
.length
] = queue
[q
];
694 // Mark registered modules as loading
695 if ( queue
[q
] in registry
) {
696 registry
[queue
[q
]].state
= 'loading';
701 // Early exit if there's nothing to load
702 if ( !batch
.length
) {
705 // Clean up the queue
707 // Always order modules alphabetically to help reduce cache
708 // misses for otherwise identical content
710 // Build a list of request parameters
712 'skin': mw
.config
.get( 'skin' ),
713 'lang': mw
.config
.get( 'wgUserLanguage' ),
714 'debug': mw
.config
.get( 'debug' )
716 // Extend request parameters with a list of modules in the batch
720 for ( var b
= 0; b
< batch
.length
; b
++ ) {
721 var group
= registry
[batch
[b
]].group
;
722 if ( !( group
in groups
) ) {
725 groups
[group
][groups
[group
].length
] = batch
[b
];
727 for ( var group
in groups
) {
728 // Calculate the highest timestamp
730 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
731 if ( registry
[groups
[group
][g
]].version
> version
) {
732 version
= registry
[groups
[group
][g
]].version
;
735 var reqBase
= $.extend( { 'version': formatVersionNumber( version
) }, base
);
736 var reqBaseLength
= $.param( reqBase
).length
;
738 var limit
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
739 // We may need to split up the request to honor the query string length limit
740 // So build it piece by piece
741 var l
= reqBaseLength
+ 9; // '&modules='.length == 9
743 reqs
[0] = {}; // { prefix: [ suffixes ] }
744 for ( var i
= 0; i
< groups
[group
].length
; i
++ ) {
745 // Determine how many bytes this module would add to the query string
746 var lastDotIndex
= groups
[group
][i
].lastIndexOf( '.' );
747 // Note that these substr() calls work even if lastDotIndex == -1
748 var prefix
= groups
[group
][i
].substr( 0, lastDotIndex
);
749 var suffix
= groups
[group
][i
].substr( lastDotIndex
+ 1 );
750 var bytesAdded
= prefix
in reqs
[r
] ?
751 suffix
.length
+ 3 : // '%2C'.length == 3
752 groups
[group
][i
].length
+ 3; // '%7C'.length == 3
754 // If the request would become too long, create a new one,
755 // but don't create empty requests
756 if ( limit
> 0 && reqs
[r
] != {} && l
+ bytesAdded
> limit
) {
757 // This request would become too long, create a new one
760 l
= reqBaseLength
+ 9;
762 if ( !( prefix
in reqs
[r
] ) ) {
763 reqs
[r
][prefix
] = [];
765 reqs
[r
][prefix
].push( suffix
);
768 for ( var r
= 0; r
< reqs
.length
; r
++ ) {
769 requests
[requests
.length
] = $.extend(
770 { 'modules': buildModulesString( reqs
[r
] ) }, reqBase
774 // Clear the batch - this MUST happen before we append the
775 // script element to the body or it's possible that the script
776 // will be locally cached, instantly load, and work the batch
777 // again, all before we've cleared it causing each request to
778 // include modules which are already loaded
780 // Asynchronously append a script tag to the end of the body
781 for ( var r
= 0; r
< requests
.length
; r
++ ) {
782 requests
[r
] = sortQuery( requests
[r
] );
783 var src
= mw
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
789 * Registers a module, letting the system know about it and its
790 * dependencies. loader.js files contain calls to this function.
792 this.register = function( module
, version
, dependencies
, group
) {
793 // Allow multiple registration
794 if ( typeof module
=== 'object' ) {
795 for ( var m
= 0; m
< module
.length
; m
++ ) {
796 if ( typeof module
[m
] === 'string' ) {
797 mw
.loader
.register( module
[m
] );
798 } else if ( typeof module
[m
] === 'object' ) {
799 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
805 if ( typeof module
!== 'string' ) {
806 throw new Error( 'module must be a string, not a ' + typeof module
);
808 if ( typeof registry
[module
] !== 'undefined' ) {
809 throw new Error( 'module already implemented: ' + module
);
811 // List the module as registered
813 'state': 'registered',
814 'group': typeof group
=== 'string' ? group
: null,
816 'version': typeof version
!== 'undefined' ? parseInt( version
, 10 ) : 0
818 if ( typeof dependencies
=== 'string' ) {
819 // Allow dependencies to be given as a single module name
820 registry
[module
].dependencies
= [dependencies
];
821 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
822 // Allow dependencies to be given as an array of module names
823 // or a function which returns an array
824 registry
[module
].dependencies
= dependencies
;
829 * Implements a module, giving the system a course of action to take
830 * upon loading. Results of a request for one or more modules contain
831 * calls to this function.
833 * All arguments are required.
835 * @param module String: Name of module
836 * @param script Mixed: Function of module code or String of URL to be used as the src
837 * attribute when adding a script element to the body
838 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
839 * keyed by media-type
840 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
842 this.implement = function( module
, script
, style
, msgs
) {
844 if ( typeof module
!== 'string' ) {
845 throw new Error( 'module must be a string, not a ' + typeof module
);
847 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
848 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
850 if ( !$.isPlainObject( style
) ) {
851 throw new Error( 'style must be an object, not a ' + typeof style
);
853 if ( !$.isPlainObject( msgs
) ) {
854 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
856 // Automatically register module
857 if ( typeof registry
[module
] === 'undefined' ) {
858 mw
.loader
.register( module
);
860 // Check for duplicate implementation
861 if ( typeof registry
[module
] !== 'undefined'
862 && typeof registry
[module
].script
!== 'undefined' )
864 throw new Error( 'module already implemeneted: ' + module
);
866 // Mark module as loaded
867 registry
[module
].state
= 'loaded';
869 registry
[module
].script
= script
;
870 registry
[module
].style
= style
;
871 registry
[module
].messages
= msgs
;
872 // Execute or queue callback
874 filter( ['ready'], registry
[module
].dependencies
),
875 registry
[module
].dependencies
) )
884 * Executes a function as soon as one or more required modules are ready
886 * @param dependencies string or array of strings of modules names the callback
887 * dependencies to be ready before
889 * @param ready function callback to execute when all dependencies are ready (optional)
890 * @param error function callback to execute when if dependencies have a errors (optional)
892 this.using = function( dependencies
, ready
, error
) {
894 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
895 throw new Error( 'dependencies must be a string or an array, not a ' +
896 typeof dependencies
);
898 // Allow calling with a single dependency as a string
899 if ( typeof dependencies
=== 'string' ) {
900 dependencies
= [dependencies
];
902 // Resolve entire dependency map
903 dependencies
= resolve( dependencies
);
904 // If all dependencies are met, execute ready immediately
905 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
906 if ( $.isFunction( ready
) ) {
910 // If any dependencies have errors execute error immediately
911 else if ( filter( ['error'], dependencies
).length
) {
912 if ( $.isFunction( error
) ) {
916 // Since some dependencies are not yet ready, queue up a request
918 request( dependencies
, ready
, error
);
923 * Loads an external script or one or more modules for future use
925 * @param modules mixed either the name of a module, array of modules,
926 * or a URL of an external script or style
927 * @param type string mime-type to use if calling with a URL of an
928 * external script or style; acceptable values are "text/css" and
929 * "text/javascript"; if no type is provided, text/javascript is
932 this.load = function( modules
, type
) {
934 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
935 throw new Error( 'modules must be a string or an array, not a ' +
938 // Allow calling with an external script or single dependency as a string
939 if ( typeof modules
=== 'string' ) {
940 // Support adding arbitrary external scripts
941 if ( modules
.substr( 0, 7 ) == 'http://' || modules
.substr( 0, 8 ) == 'https://' ) {
942 if ( type
=== 'text/css' ) {
943 $( 'head' ).append( $( '<link />', {
949 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
950 addScript( modules
);
956 // Called with single module
959 // Resolve entire dependency map
960 modules
= resolve( modules
);
961 // If all modules are ready, nothing dependency be done
962 if ( compare( filter( ['ready'], modules
), modules
) ) {
965 // If any modules have errors return false
966 else if ( filter( ['error'], modules
).length
) {
969 // Since some modules are not yet ready, queue up a request
977 * Changes the state of a module
979 * @param module string module name or object of module name/state pairs
980 * @param state string state name
982 this.state = function( module
, state
) {
983 if ( typeof module
=== 'object' ) {
984 for ( var m
in module
) {
985 mw
.loader
.state( m
, module
[m
] );
989 if ( !( module
in registry
) ) {
990 mw
.loader
.register( module
);
992 registry
[module
].state
= state
;
996 * Gets the version of a module
998 * @param module string name of module to get version for
1000 this.getVersion = function( module
) {
1001 if ( module
in registry
&& 'version' in registry
[module
] ) {
1002 return formatVersionNumber( registry
[module
].version
);
1007 * @deprecated use mw.loader.getVersion() instead
1009 this.version = function() {
1010 return mediaWiki
.loader
.getVersion
.apply( mediaWiki
.loader
, arguments
);
1014 * Gets the state of a module
1016 * @param module string name of module to get state for
1018 this.getState = function( module
) {
1019 if ( module
in registry
&& 'state' in registry
[module
] ) {
1020 return registry
[module
].state
;
1025 /* Cache document ready status */
1027 $(document
).ready( function() { ready
= true; } );
1030 /** HTML construction helper functions */
1031 this.html
= new ( function () {
1032 var escapeCallback = function( s
) {
1048 * Escape a string for HTML. Converts special characters to HTML entities.
1049 * @param s The string to escape
1051 this.escape = function( s
) {
1052 return s
.replace( /['"<>&]/g, escapeCallback
);
1056 * Wrapper object for raw HTML passed to mw.html.element().
1058 this.Raw = function( value
) {
1063 * Wrapper object for CDATA element contents passed to mw.html.element()
1065 this.Cdata = function( value
) {
1070 * Create an HTML element string, with safe escaping.
1072 * @param name The tag name.
1073 * @param attrs An object with members mapping element names to values
1074 * @param contents The contents of the element. May be either:
1075 * - string: The string is escaped.
1076 * - null or undefined: The short closing form is used, e.g. <br/>.
1077 * - this.Raw: The value attribute is included without escaping.
1078 * - this.Cdata: The value attribute is included, and an exception is
1079 * thrown if it contains an illegal ETAGO delimiter.
1080 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1084 * return h.element( 'div', {},
1085 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1086 * Returns <div><img src="<"/></div>
1088 this.element = function( name
, attrs
, contents
) {
1090 for ( var attrName
in attrs
) {
1091 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1093 if ( typeof contents
== 'undefined' || contents
=== null ) {
1100 if ( typeof contents
=== 'string') {
1102 s
+= this.escape( contents
);
1103 } else if ( contents
instanceof this.Raw
) {
1104 // Raw HTML inclusion
1105 s
+= contents
.value
;
1106 } else if ( contents
instanceof this.Cdata
) {
1108 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1109 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1111 s
+= contents
.value
;
1113 throw new Error( 'mw.html.element: Invalid type of contents' );
1115 s
+= '</' + name
+ '>';
1120 /* Extension points */
1126 // Alias $j to jQuery for backwards compatibility
1128 window
.mw
= mediaWiki
;
1130 /* Auto-register from pre-loaded startup scripts */
1132 if ( $.isFunction( startUp
) ) {