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.getScript
689 script
.onload
= script
.onreadystatechange = function() {
694 || this.readyState
=== 'loaded'
695 || this.readyState
=== 'complete'
700 // Handle memory leak in IE
701 script
.onload
= script
.onreadystatechange
= null;
702 if ( script
.parentNode
) {
703 script
.parentNode
.removeChild( script
);
708 document
.body
.appendChild( script
);
710 document
.write( mw
.html
.element(
711 'script', { 'type': 'text/javascript', 'src': src
}, ''
713 if ( $.isFunction( callback
) ) {
714 // Document.write is synchronous, so this is called when it's done
723 * Requests dependencies from server, loading and executing when things when ready.
725 this.work = function() {
726 // Build a list of request parameters
728 'skin': mw
.config
.get( 'skin' ),
729 'lang': mw
.config
.get( 'wgUserLanguage' ),
730 'debug': mw
.config
.get( 'debug' )
732 // Extend request parameters with a list of modules in the batch
737 // Appends a list of modules to the batch
738 for ( var q
= 0; q
< queue
.length
; q
++ ) {
739 // Only request modules which are undefined or registered
740 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
=== 'registered' ) {
741 // Prevent duplicate entries
742 if ( $.inArray( queue
[q
], batch
) === -1 ) {
743 batch
[batch
.length
] = queue
[q
];
744 // Mark registered modules as loading
745 if ( queue
[q
] in registry
) {
746 registry
[queue
[q
]].state
= 'loading';
751 // Early exit if there's nothing to load
752 if ( !batch
.length
) {
755 // Clean up the queue
757 // Always order modules alphabetically to help reduce cache
758 // misses for otherwise identical content
760 for ( var b
= 0; b
< batch
.length
; b
++ ) {
761 var bGroup
= registry
[batch
[b
]].group
;
762 if ( !( bGroup
in groups
) ) {
765 groups
[bGroup
][groups
[bGroup
].length
] = batch
[b
];
767 for ( var group
in groups
) {
768 // Calculate the highest timestamp
770 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
771 if ( registry
[groups
[group
][g
]].version
> version
) {
772 version
= registry
[groups
[group
][g
]].version
;
776 var reqBase
= $.extend( { 'version': formatVersionNumber( version
) }, base
),
777 reqBaseLength
= $.param( reqBase
).length
,
779 limit
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 ),
780 // We may need to split up the request to honor the query string length limit,
781 // so build it piece by piece.
782 l
= reqBaseLength
+ 9, // '&modules='.length == 9
785 reqs
[0] = {}; // { prefix: [ suffixes ] }
787 for ( var i
= 0; i
< groups
[group
].length
; i
++ ) {
788 // Determine how many bytes this module would add to the query string
789 var lastDotIndex
= groups
[group
][i
].lastIndexOf( '.' ),
790 // Note that these substr() calls work even if lastDotIndex == -1
791 prefix
= groups
[group
][i
].substr( 0, lastDotIndex
),
792 suffix
= groups
[group
][i
].substr( lastDotIndex
+ 1 ),
793 bytesAdded
= prefix
in reqs
[r
]
794 ? suffix
.length
+ 3 // '%2C'.length == 3
795 : groups
[group
][i
].length
+ 3; // '%7C'.length == 3
797 // If the request would become too long, create a new one,
798 // but don't create empty requests
799 if ( limit
> 0 && !$.isEmptyObject( reqs
[r
] ) && l
+ bytesAdded
> limit
) {
800 // This request would become too long, create a new one
803 l
= reqBaseLength
+ 9;
805 if ( !( prefix
in reqs
[r
] ) ) {
806 reqs
[r
][prefix
] = [];
808 reqs
[r
][prefix
].push( suffix
);
811 for ( var r
= 0; r
< reqs
.length
; r
++ ) {
812 requests
[requests
.length
] = $.extend(
813 { 'modules': buildModulesString( reqs
[r
] ) }, reqBase
817 // Clear the batch - this MUST happen before we append the
818 // script element to the body or it's possible that the script
819 // will be locally cached, instantly load, and work the batch
820 // again, all before we've cleared it causing each request to
821 // include modules which are already loaded
823 // Asynchronously append a script tag to the end of the body
824 for ( var r
= 0; r
< requests
.length
; r
++ ) {
825 requests
[r
] = sortQuery( requests
[r
] );
826 // Append &* to avoid triggering the IE6 extension check
827 var src
= mw
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] ) + '&*';
833 * Registers a module, letting the system know about it and its
834 * dependencies. loader.js files contain calls to this function.
836 this.register = function( module
, version
, dependencies
, group
) {
837 // Allow multiple registration
838 if ( typeof module
=== 'object' ) {
839 for ( var m
= 0; m
< module
.length
; m
++ ) {
840 if ( typeof module
[m
] === 'string' ) {
841 mw
.loader
.register( module
[m
] );
842 } else if ( typeof module
[m
] === 'object' ) {
843 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
849 if ( typeof module
!== 'string' ) {
850 throw new Error( 'module must be a string, not a ' + typeof module
);
852 if ( registry
[module
] !== undefined ) {
853 throw new Error( 'module already implemented: ' + module
);
855 // List the module as registered
857 'state': 'registered',
858 'group': typeof group
=== 'string' ? group
: null,
860 'version': version
!== undefined ? parseInt( version
, 10 ) : 0
862 if ( typeof dependencies
=== 'string' ) {
863 // Allow dependencies to be given as a single module name
864 registry
[module
].dependencies
= [dependencies
];
865 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
866 // Allow dependencies to be given as an array of module names
867 // or a function which returns an array
868 registry
[module
].dependencies
= dependencies
;
873 * Implements a module, giving the system a course of action to take
874 * upon loading. Results of a request for one or more modules contain
875 * calls to this function.
877 * All arguments are required.
879 * @param module String: Name of module
880 * @param script Mixed: Function of module code or String of URL to be used as the src
881 * attribute when adding a script element to the body
882 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
883 * keyed by media-type
884 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
886 this.implement = function( module
, script
, style
, msgs
) {
888 if ( typeof module
!== 'string' ) {
889 throw new Error( 'module must be a string, not a ' + typeof module
);
891 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
892 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
894 if ( !$.isPlainObject( style
) ) {
895 throw new Error( 'style must be an object, not a ' + typeof style
);
897 if ( !$.isPlainObject( msgs
) ) {
898 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
900 // Automatically register module
901 if ( registry
[module
] === undefined ) {
902 mw
.loader
.register( module
);
904 // Check for duplicate implementation
905 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
906 throw new Error( 'module already implemeneted: ' + module
);
908 // Mark module as loaded
909 registry
[module
].state
= 'loaded';
911 registry
[module
].script
= script
;
912 registry
[module
].style
= style
;
913 registry
[module
].messages
= msgs
;
914 // Execute or queue callback
916 filter( ['ready'], registry
[module
].dependencies
),
917 registry
[module
].dependencies
) )
926 * Executes a function as soon as one or more required modules are ready
928 * @param dependencies string or array of strings of modules names the callback
929 * dependencies to be ready before executing
930 * @param ready function callback to execute when all dependencies are ready (optional)
931 * @param error function callback to execute when if dependencies have a errors (optional)
933 this.using = function( dependencies
, ready
, error
) {
934 var tod
= typeof dependencies
;
936 if ( tod
!== 'object' && tod
!== 'string' ) {
937 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
939 // Allow calling with a single dependency as a string
940 if ( tod
=== 'string' ) {
941 dependencies
= [dependencies
];
943 // Resolve entire dependency map
944 dependencies
= resolve( dependencies
);
945 // If all dependencies are met, execute ready immediately
946 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
947 if ( $.isFunction( ready
) ) {
951 // If any dependencies have errors execute error immediately
952 else if ( filter( ['error'], dependencies
).length
) {
953 if ( $.isFunction( error
) ) {
957 // Since some dependencies are not yet ready, queue up a request
959 request( dependencies
, ready
, error
);
964 * Loads an external script or one or more modules for future use
966 * @param modules mixed either the name of a module, array of modules,
967 * or a URL of an external script or style
968 * @param type string mime-type to use if calling with a URL of an
969 * external script or style; acceptable values are "text/css" and
970 * "text/javascript"; if no type is provided, text/javascript is assumed.
972 this.load = function( modules
, type
) {
974 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
975 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
977 // Allow calling with an external script or single dependency as a string
978 if ( typeof modules
=== 'string' ) {
979 // Support adding arbitrary external scripts
980 if ( modules
.substr( 0, 7 ) === 'http://' || modules
.substr( 0, 8 ) === 'https://' ) {
981 if ( type
=== 'text/css' ) {
982 $( 'head' ).append( $( '<link/>', {
988 } else if ( type
=== 'text/javascript' || type
=== undefined ) {
989 addScript( modules
);
995 // Called with single module
998 // Resolve entire dependency map
999 modules
= resolve( modules
);
1000 // If all modules are ready, nothing dependency be done
1001 if ( compare( filter( ['ready'], modules
), modules
) ) {
1004 // If any modules have errors return false
1005 else if ( filter( ['error'], modules
).length
) {
1008 // Since some modules are not yet ready, queue up a request
1016 * Changes the state of a module
1018 * @param module string module name or object of module name/state pairs
1019 * @param state string state name
1021 this.state = function( module
, state
) {
1022 if ( typeof module
=== 'object' ) {
1023 for ( var m
in module
) {
1024 mw
.loader
.state( m
, module
[m
] );
1028 if ( !( module
in registry
) ) {
1029 mw
.loader
.register( module
);
1031 registry
[module
].state
= state
;
1035 * Gets the version of a module
1037 * @param module string name of module to get version for
1039 this.getVersion = function( module
) {
1040 if ( module
in registry
&& 'version' in registry
[module
] ) {
1041 return formatVersionNumber( registry
[module
].version
);
1047 * @deprecated use mw.loader.getVersion() instead
1049 this.version = function() {
1050 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1054 * Gets the state of a module
1056 * @param module string name of module to get state for
1058 this.getState = function( module
) {
1059 if ( module
in registry
&& 'state' in registry
[module
] ) {
1060 return registry
[module
].state
;
1065 /* Cache document ready status */
1067 $(document
).ready( function() { ready
= true; } );
1070 /** HTML construction helper functions */
1071 this.html
= new ( function () {
1072 var escapeCallback = function( s
) {
1088 * Escape a string for HTML. Converts special characters to HTML entities.
1089 * @param s The string to escape
1091 this.escape = function( s
) {
1092 return s
.replace( /['"<>&]/g, escapeCallback
);
1096 * Wrapper object for raw HTML passed to mw.html.element().
1098 this.Raw = function( value
) {
1103 * Wrapper object for CDATA element contents passed to mw.html.element()
1105 this.Cdata = function( value
) {
1110 * Create an HTML element string, with safe escaping.
1112 * @param name The tag name.
1113 * @param attrs An object with members mapping element names to values
1114 * @param contents The contents of the element. May be either:
1115 * - string: The string is escaped.
1116 * - null or undefined: The short closing form is used, e.g. <br/>.
1117 * - this.Raw: The value attribute is included without escaping.
1118 * - this.Cdata: The value attribute is included, and an exception is
1119 * thrown if it contains an illegal ETAGO delimiter.
1120 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1124 * return h.element( 'div', {},
1125 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1126 * Returns <div><img src="<"/></div>
1128 this.element = function( name
, attrs
, contents
) {
1130 for ( var attrName
in attrs
) {
1131 s
+= ' ' + attrName
+ '="' + this.escape( attrs
[attrName
] ) + '"';
1133 if ( contents
=== undefined || contents
=== null ) {
1140 if ( typeof contents
=== 'string' ) {
1142 s
+= this.escape( contents
);
1143 } else if ( contents
instanceof this.Raw
) {
1144 // Raw HTML inclusion
1145 s
+= contents
.value
;
1146 } else if ( contents
instanceof this.Cdata
) {
1148 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1149 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1151 s
+= contents
.value
;
1153 throw new Error( 'mw.html.element: Invalid type of contents' );
1155 s
+= '</' + name
+ '>';
1160 /* Extension points */
1166 // Alias $j to jQuery for backwards compatibility
1169 // Auto-register from pre-loaded startup scripts
1170 if ( jQuery
.isFunction( startUp
) ) {