2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
10 /*jshint latedef:false */
15 hasOwn
= Object
.prototype.hasOwnProperty
,
16 slice
= Array
.prototype.slice
,
17 trackCallbacks
= $.Callbacks( 'memory' ),
22 * FNV132 hash function
24 * This function implements the 32-bit version of FNV-1.
25 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
26 * its output is base 36 rather than hex.
27 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
30 * @param {string} str String to hash
31 * @return {string} hash as an seven-character base 36 string
33 function fnv132( str
) {
34 /*jshint bitwise:false */
35 var hash
= 0x811C9DC5,
38 for ( i
= 0; i
< str
.length
; i
++ ) {
39 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
40 hash
^= str
.charCodeAt( i
);
43 hash
= ( hash
>>> 0 ).toString( 36 );
44 while ( hash
.length
< 7 ) {
52 * Create an object that can be read from or written to from methods that allow
53 * interaction both with single and multiple properties at once.
57 * var collection, query, results;
59 * // Create your address book
60 * collection = new mw.Map();
62 * // This data could be coming from an external source (eg. API/AJAX)
64 * 'John Doe': 'john@example.org',
65 * 'Jane Doe': 'jane@example.org',
66 * 'George van Halen': 'gvanhalen@example.org'
69 * wanted = ['John Doe', 'Jane Doe', 'Daniel Jackson'];
71 * // You can detect missing keys first
72 * if ( !collection.exists( wanted ) ) {
73 * // One or more are missing (in this case: "Daniel Jackson")
74 * mw.log( 'One or more names were not found in your address book' );
77 * // Or just let it give you what it can. Optionally fill in from a default.
78 * results = collection.get( wanted, 'nobody@example.com' );
79 * mw.log( results['Jane Doe'] ); // "jane@example.org"
80 * mw.log( results['Daniel Jackson'] ); // "nobody@example.com"
85 * @param {Object|boolean} [values] The value-baring object to be mapped. Defaults to an
87 * For backwards-compatibility with mw.config, this can also be `true` in which case values
88 * are copied to the Window object as global variables (T72470). Values are copied in
89 * one direction only. Changes to globals are not reflected in the map.
91 function Map( values
) {
92 if ( values
=== true ) {
95 // Override #set to also set the global variable
96 this.set = function ( selection
, value
) {
99 if ( $.isPlainObject( selection
) ) {
100 for ( s
in selection
) {
101 setGlobalMapValue( this, s
, selection
[ s
] );
105 if ( typeof selection
=== 'string' && arguments
.length
) {
106 setGlobalMapValue( this, selection
, value
);
115 this.values
= values
|| {};
119 * Alias property to the global object.
123 * @param {mw.Map} map
124 * @param {string} key
125 * @param {Mixed} value
127 function setGlobalMapValue( map
, key
, value
) {
128 map
.values
[ key
] = value
;
133 // Deprecation notice for mw.config globals (T58550, T72470)
134 map
=== mw
.config
&& 'Use mw.config instead.'
140 * Get the value of one or more keys.
142 * If called with no arguments, all values are returned.
144 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
145 * @param {Mixed} [fallback=null] Value for keys that don't exist.
146 * @return {Mixed|Object| null} If selection was a string, returns the value,
147 * If selection was an array, returns an object of key/values.
148 * If no selection is passed, the 'values' container is returned. (Beware that,
149 * as is the default in JavaScript, the object is returned by reference.)
151 get: function ( selection
, fallback
) {
153 // If we only do this in the `return` block, it'll fail for the
154 // call to get() from the mutli-selection block.
155 fallback
= arguments
.length
> 1 ? fallback
: null;
157 if ( $.isArray( selection
) ) {
158 selection
= slice
.call( selection
);
160 for ( i
= 0; i
< selection
.length
; i
++ ) {
161 results
[ selection
[ i
] ] = this.get( selection
[ i
], fallback
);
166 if ( typeof selection
=== 'string' ) {
167 if ( !hasOwn
.call( this.values
, selection
) ) {
170 return this.values
[ selection
];
173 if ( selection
=== undefined ) {
177 // Invalid selection key
182 * Set one or more key/value pairs.
184 * @param {string|Object} selection Key to set value for, or object mapping keys to values
185 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
186 * @return {boolean} True on success, false on failure
188 set: function ( selection
, value
) {
191 if ( $.isPlainObject( selection
) ) {
192 for ( s
in selection
) {
193 this.values
[ s
] = selection
[ s
];
197 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
198 this.values
[ selection
] = value
;
205 * Check if one or more keys exist.
207 * @param {Mixed} selection Key or array of keys to check
208 * @return {boolean} True if the key(s) exist
210 exists: function ( selection
) {
213 if ( $.isArray( selection
) ) {
214 for ( s
= 0; s
< selection
.length
; s
++ ) {
215 if ( typeof selection
[ s
] !== 'string' || !hasOwn
.call( this.values
, selection
[ s
] ) ) {
221 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
226 * Object constructor for messages.
228 * Similar to the Message class in MediaWiki PHP.
230 * Format defaults to 'text'.
236 * 'hello': 'Hello world',
237 * 'hello-user': 'Hello, $1!',
238 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
241 * obj = new mw.Message( mw.messages, 'hello' );
242 * mw.log( obj.text() );
245 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
246 * mw.log( obj.text() );
247 * // Hello, John Doe!
249 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
250 * mw.log( obj.text() );
251 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
253 * // Using mw.message shortcut
254 * obj = mw.message( 'hello-user', 'John Doe' );
255 * mw.log( obj.text() );
256 * // Hello, John Doe!
258 * // Using mw.msg shortcut
259 * str = mw.msg( 'hello-user', 'John Doe' );
261 * // Hello, John Doe!
263 * // Different formats
264 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
266 * obj.format = 'text';
267 * str = obj.toString();
272 * // Hello, John "Wiki" <3 Doe!
274 * mw.log( obj.escaped() );
275 * // Hello, John "Wiki" <3 Doe!
280 * @param {mw.Map} map Message store
281 * @param {string} key
282 * @param {Array} [parameters]
284 function Message( map
, key
, parameters
) {
285 this.format
= 'text';
288 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
292 Message
.prototype = {
294 * Get parsed contents of the message.
296 * The default parser does simple $N replacements and nothing else.
297 * This may be overridden to provide a more complex message parser.
298 * The primary override is in the mediawiki.jqueryMsg module.
300 * This function will not be called for nonexistent messages.
302 * @return {string} Parsed message
304 parser: function () {
305 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
309 * Add (does not replace) parameters for `$N` placeholder values.
311 * @param {Array} parameters
314 params: function ( parameters
) {
316 for ( i
= 0; i
< parameters
.length
; i
++ ) {
317 this.parameters
.push( parameters
[ i
] );
323 * Convert message object to its string form based on current format.
325 * @return {string} Message as a string in the current form, or `<key>` if key
328 toString: function () {
331 if ( !this.exists() ) {
332 // Use <key> as text if key does not exist
333 if ( this.format
=== 'escaped' || this.format
=== 'parse' ) {
334 // format 'escaped' and 'parse' need to have the brackets and key html escaped
335 return mw
.html
.escape( '<' + this.key
+ '>' );
337 return '<' + this.key
+ '>';
340 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
341 text
= this.parser();
344 if ( this.format
=== 'escaped' ) {
345 text
= this.parser();
346 text
= mw
.html
.escape( text
);
353 * Change format to 'parse' and convert message to string
355 * If jqueryMsg is loaded, this parses the message text from wikitext
356 * (where supported) to HTML
358 * Otherwise, it is equivalent to plain.
360 * @return {string} String form of parsed message
363 this.format
= 'parse';
364 return this.toString();
368 * Change format to 'plain' and convert message to string
370 * This substitutes parameters, but otherwise does not change the
373 * @return {string} String form of plain message
376 this.format
= 'plain';
377 return this.toString();
381 * Change format to 'text' and convert message to string
383 * If jqueryMsg is loaded, {{-transformation is done where supported
384 * (such as {{plural:}}, {{gender:}}, {{int:}}).
386 * Otherwise, it is equivalent to plain
388 * @return {string} String form of text message
391 this.format
= 'text';
392 return this.toString();
396 * Change the format to 'escaped' and convert message to string
398 * This is equivalent to using the 'text' format (see #text), then
399 * HTML-escaping the output.
401 * @return {string} String form of html escaped message
403 escaped: function () {
404 this.format
= 'escaped';
405 return this.toString();
409 * Check if a message exists
414 exists: function () {
415 return this.map
.exists( this.key
);
425 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
427 * On browsers that implement the Navigation Timing API, this function will produce floating-point
428 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
429 * it will fall back to using `Date`.
431 * @return {number} Current time
434 var perf
= window
.performance
,
435 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
436 return navStart
&& typeof perf
.now
=== 'function' ?
437 function () { return navStart
+ perf
.now(); } :
438 function () { return +new Date(); };
442 * Format a string. Replace $1, $2 ... $N with positional arguments.
444 * Used by Message#parser().
447 * @param {string} formatString Format string
448 * @param {...Mixed} parameters Values for $N replacements
449 * @return {string} Formatted string
451 format: function ( formatString
) {
452 var parameters
= slice
.call( arguments
, 1 );
453 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
454 var index
= parseInt( match
, 10 ) - 1;
455 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
460 * Track an analytic event.
462 * This method provides a generic means for MediaWiki JavaScript code to capture state
463 * information for analysis. Each logged event specifies a string topic name that describes
464 * the kind of event that it is. Topic names consist of dot-separated path components,
465 * arranged from most general to most specific. Each path component should have a clear and
466 * well-defined purpose.
468 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
469 * events that match their subcription, including those that fired before the handler was
472 * @param {string} topic Topic name
473 * @param {Object} [data] Data describing the event, encoded as an object
475 track: function ( topic
, data
) {
476 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
477 trackCallbacks
.fire( trackQueue
);
481 * Register a handler for subset of analytic events, specified by topic.
483 * Handlers will be called once for each tracked event, including any events that fired before the
484 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
485 * the exact time at which the event fired, a string 'topic' property naming the event, and a
486 * 'data' property which is an object of event-specific data. The event topic and event data are
487 * also passed to the callback as the first and second arguments, respectively.
489 * @param {string} topic Handle events whose name starts with this string prefix
490 * @param {Function} callback Handler to call for each matching tracked event
491 * @param {string} callback.topic
492 * @param {Object} [callback.data]
494 trackSubscribe: function ( topic
, callback
) {
496 function handler( trackQueue
) {
498 for ( ; seen
< trackQueue
.length
; seen
++ ) {
499 event
= trackQueue
[ seen
];
500 if ( event
.topic
.indexOf( topic
) === 0 ) {
501 callback
.call( event
, event
.topic
, event
.data
);
506 trackHandlers
.push( [ handler
, callback
] );
508 trackCallbacks
.add( handler
);
512 * Stop handling events for a particular handler
514 * @param {Function} callback
516 trackUnsubscribe: function ( callback
) {
517 trackHandlers
= $.grep( trackHandlers
, function ( fns
) {
518 if ( fns
[ 1 ] === callback
) {
519 trackCallbacks
.remove( fns
[ 0 ] );
520 // Ensure the tuple is removed to avoid holding on to closures
527 // Expose Map constructor
530 // Expose Message constructor
534 * Map of configuration values.
536 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
539 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
540 * global `window` object.
542 * @property {mw.Map} config
544 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
548 * Empty object for third-party libraries, for cases where you don't
549 * want to add a new global, or the global is bad and needs containment
557 * Access container for deprecated functionality that can be moved from
558 * from their legacy location and attached to this object (e.g. a global
559 * function that is deprecated and as stop-gap can be exposed through here).
561 * This was reserved for future use but never ended up being used.
563 * @deprecated since 1.22 Let deprecated identifiers keep their original name
564 * and use mw.log#deprecate to create an access container for tracking.
570 * Store for messages.
577 * Store for templates associated with a module.
581 templates
: new Map(),
584 * Get a message object.
586 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
589 * @param {string} key Key of message to get
590 * @param {...Mixed} parameters Values for $N replacements
591 * @return {mw.Message}
593 message: function ( key
) {
594 var parameters
= slice
.call( arguments
, 1 );
595 return new Message( mw
.messages
, key
, parameters
);
599 * Get a message string using the (default) 'text' format.
601 * Shortcut for `mw.message( key, parameters... ).text()`.
604 * @param {string} key Key of message to get
605 * @param {...Mixed} parameters Values for $N replacements
609 return mw
.message
.apply( mw
.message
, arguments
).toString();
613 * Dummy placeholder for {@link mw.log}
618 // Also update the restoration of methods in mediawiki.log.js
619 // when adding or removing methods here.
620 var log = function () {},
621 console
= window
.console
;
629 * Write a message to the console's warning channel.
630 * Actions not supported by the browser console are silently ignored.
632 * @param {...string} msg Messages to output to console
634 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
635 Function
.prototype.bind
.call( console
.warn
, console
) :
639 * Write a message to the console's error channel.
641 * Most browsers provide a stacktrace by default if the argument
642 * is a caught Error object.
645 * @param {Error|...string} msg Messages to output to console
647 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
648 Function
.prototype.bind
.call( console
.error
, console
) :
652 * Create a property in a host object that, when accessed, will produce
653 * a deprecation warning in the console with backtrace.
655 * @param {Object} obj Host object of deprecated property
656 * @param {string} key Name of property to create in `obj`
657 * @param {Mixed} val The value this property should return when accessed
658 * @param {string} [msg] Optional text to include in the deprecation message
660 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
662 } : function ( obj
, key
, val
, msg
) {
664 msg
= 'Use of "' + key
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
665 var logged
, loggedIsSet
, uniqueTrace
;
673 uniqueTrace = function () {
674 var trace
= new Error().stack
;
676 if ( logged
.has( trace
) ) {
682 if ( logged
.hasOwnProperty( trace
) ) {
689 Object
.defineProperty( obj
, key
, {
693 if ( uniqueTrace() ) {
694 mw
.track( 'mw.deprecate', key
);
699 set: function ( newVal
) {
700 if ( uniqueTrace() ) {
701 mw
.track( 'mw.deprecate', key
);
714 * Client for ResourceLoader server end point.
716 * This client is in charge of maintaining the module registry and state
717 * machine, initiating network (batch) requests for loading modules, as
718 * well as dependency resolution and execution of source code.
720 * For more information, refer to
721 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
726 loader
: ( function () {
729 * Fired via mw.track on various resource loading errors.
731 * @event resourceloader_exception
732 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
733 * object, but in theory module code could manually throw something else, and that
734 * might also end up here.
735 * @param {string} [module] Name of the module which caused the error. Omitted if the
736 * error is not module-related or the module cannot be easily identified due to
738 * @param {string} source Source of the error. Possible values:
740 * - style: stylesheet error (only affects old IE where a special style loading method
742 * - load-callback: exception thrown by user callback
743 * - module-execute: exception thrown by module code
744 * - store-eval: could not evaluate module code cached in localStorage
745 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
746 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
747 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
751 * Fired via mw.track on resource loading error conditions.
753 * @event resourceloader_assert
754 * @param {string} source Source of the error. Possible values:
756 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
757 * bug; see <https://phabricator.wikimedia.org/T59567> for details
761 * Mapping of registered modules.
763 * See #implement and #execute for exact details on support for script, style and messages.
769 * // From mw.loader.register()
770 * 'version': '########' (hash)
771 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
772 * 'group': 'somegroup', (or) null
773 * 'source': 'local', (or) 'anotherwiki'
774 * 'skip': 'return !!window.Example', (or) null
775 * 'module': export Object
777 * // Set from execute() or mw.loader.state()
778 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
780 * // Optionally added at run-time by mw.loader.implement()
782 * 'script': closure, array of urls, or string
783 * 'style': { ... } (see #execute)
784 * 'messages': { 'key': 'value', ... }
791 * The module is known to the system but not yet required.
792 * Meta data is registered via mw.loader#register. Calls to that method are
793 * generated server-side by the startup module.
795 * The module was required through mw.loader (either directly or as dependency of
796 * another module). The client will fetch module contents from the server.
797 * The contents are then stashed in the registry via mw.loader#implement.
799 * The module has been loaded from the server and stashed via mw.loader#implement.
800 * If the module has no more dependencies in-flight, the module will be executed
801 * immediately. Otherwise execution is deferred, controlled via #handlePending.
803 * The module is being executed.
805 * The module has been successfully executed.
807 * The module (or one of its dependencies) produced an error during execution.
809 * The module was registered client-side and requested, but the server denied knowledge
810 * of the module's existence.
816 // Mapping of sources, keyed by source-id, values are strings.
821 // 'sourceId': 'http://example.org/w/load.php'
826 // For queueModuleScript()
827 handlingPendingRequests
= false,
828 pendingRequests
= [],
830 // List of modules to be loaded
834 * List of callback jobs waiting for modules to be ready.
836 * Jobs are created by #enqueue() and run by #handlePending().
838 * Typically when a job is created for a module, the job's dependencies contain
839 * both the required module and all its recursive dependencies.
844 * 'dependencies': [ module names ],
845 * 'ready': Function callback
846 * 'error': Function callback
849 * @property {Object[]} jobs
857 // For addEmbeddedCSS()
859 cssBufferTimer
= null,
860 cssCallbacks
= $.Callbacks(),
861 isIE9
= document
.documentMode
=== 9;
863 function getMarker() {
866 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
868 mw
.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
869 marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
876 * Create a new style element and add it to the DOM.
879 * @param {string} text CSS text
880 * @param {Node} [nextNode] The element where the style tag
881 * should be inserted before
882 * @return {HTMLElement} Reference to the created style element
884 function newStyleTag( text
, nextNode
) {
885 var s
= document
.createElement( 'style' );
887 s
.appendChild( document
.createTextNode( text
) );
888 if ( nextNode
&& nextNode
.parentNode
) {
889 nextNode
.parentNode
.insertBefore( s
, nextNode
);
891 document
.getElementsByTagName( 'head' )[ 0 ].appendChild( s
);
898 * Add a bit of CSS text to the current browser page.
900 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
901 * or create a new one based on whether the given `cssText` is safe for extension.
904 * @param {string} [cssText=cssBuffer] If called without cssText,
905 * the internal buffer will be inserted instead.
906 * @param {Function} [callback]
908 function addEmbeddedCSS( cssText
, callback
) {
911 function fireCallbacks() {
912 var oldCallbacks
= cssCallbacks
;
913 // Reset cssCallbacks variable so it's not polluted by any calls to
914 // addEmbeddedCSS() from one of the callbacks (T105973)
915 cssCallbacks
= $.Callbacks();
916 oldCallbacks
.fire().empty();
920 cssCallbacks
.add( callback
);
923 // Yield once before creating the <style> tag. This lets multiple stylesheets
924 // accumulate into one buffer, allowing us to reduce how often new stylesheets
925 // are inserted in the browser. Appending a stylesheet and waiting for the
926 // browser to repaint is fairly expensive. (T47810)
928 // Don't extend the buffer if the item needs its own stylesheet.
929 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
930 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
931 // Linebreak for somewhat distinguishable sections
932 cssBuffer
+= '\n' + cssText
;
933 // TODO: Using requestAnimationFrame would perform better by not injecting
934 // styles while the browser is busy painting.
935 if ( !cssBufferTimer
) {
936 cssBufferTimer
= setTimeout( function () {
937 // Support: Firefox < 13
938 // Firefox 12 has non-standard behaviour of passing a number
939 // as first argument to a setTimeout callback.
940 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
947 // This is a scheduled flush for the buffer
949 cssBufferTimer
= null;
954 // By default, always create a new <style>. Appending text to a <style> tag is
955 // is a performance anti-pattern as it requires CSS to be reparsed (T47810).
958 // Try to re-use existing <style> tags due to the IE stylesheet limit (T33676).
960 $style
= $( getMarker() ).prev();
961 // Verify that the element before the marker actually is a <style> tag created
962 // by mw.loader (not some other style tag, or e.g. a <meta> tag).
963 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) ) {
964 styleEl
= $style
[ 0 ];
965 styleEl
.appendChild( document
.createTextNode( cssText
) );
969 // Else: No existing tag to reuse. Continue below and create the first one.
972 $style
= $( newStyleTag( cssText
, getMarker() ) );
975 $style
.data( 'ResourceLoaderDynamicStyleTag', true );
983 * @param {Array} modules List of module names
984 * @return {string} Hash of concatenated version hashes.
986 function getCombinedVersion( modules
) {
987 var hashes
= $.map( modules
, function ( module
) {
988 return registry
[ module
].version
;
990 return fnv132( hashes
.join( '' ) );
994 * Determine whether all dependencies are in state 'ready', which means we may
995 * execute the module or job now.
998 * @param {Array} modules Names of modules to be checked
999 * @return {boolean} True if all modules are in state 'ready', false otherwise
1001 function allReady( modules
) {
1003 for ( i
= 0; i
< modules
.length
; i
++ ) {
1004 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
1012 * Determine whether all dependencies are in state 'ready', which means we may
1013 * execute the module or job now.
1016 * @param {Array} modules Names of modules to be checked
1017 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1019 function anyFailed( modules
) {
1021 for ( i
= 0; i
< modules
.length
; i
++ ) {
1022 state
= mw
.loader
.getState( modules
[ i
] );
1023 if ( state
=== 'error' || state
=== 'missing' ) {
1031 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1032 * pending jobs and modules that depend upon this module. If the given module failed,
1033 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1034 * all jobs/modules now having their dependencies satisfied.
1036 * Jobs that depend on a failed module, will have their error callback ran (if any).
1039 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1041 function handlePending( module
) {
1042 var j
, job
, hasErrors
, m
, stateChange
;
1044 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1045 // If the current module failed, mark all dependent modules also as failed.
1046 // Iterate until steady-state to propagate the error state upwards in the
1049 stateChange
= false;
1050 for ( m
in registry
) {
1051 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1052 if ( anyFailed( registry
[ m
].dependencies
) ) {
1053 registry
[ m
].state
= 'error';
1058 } while ( stateChange
);
1061 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1062 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1063 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1064 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1065 // All dependencies satisfied, or some have errors
1067 jobs
.splice( j
, 1 );
1071 if ( typeof job
.error
=== 'function' ) {
1072 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1075 if ( typeof job
.ready
=== 'function' ) {
1080 // A user-defined callback raised an exception.
1081 // Swallow it to protect our state machine!
1082 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1087 if ( registry
[ module
].state
=== 'ready' ) {
1088 // The current module became 'ready'. Set it in the module store, and recursively execute all
1089 // dependent modules that are loaded and now have all dependencies satisfied.
1090 mw
.loader
.store
.set( module
, registry
[ module
] );
1091 for ( m
in registry
) {
1092 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1100 * Resolve dependencies and detect circular references.
1103 * @param {string} module Name of the top-level module whose dependencies shall be
1104 * resolved and sorted.
1105 * @param {Array} resolved Returns a topological sort of the given module and its
1106 * dependencies, such that later modules depend on earlier modules. The array
1107 * contains the module names. If the array contains already some module names,
1108 * this function appends its result to the pre-existing array.
1109 * @param {Object} [unresolved] Hash used to track the current dependency
1110 * chain; used to report loops in the dependency graph.
1111 * @throws {Error} If any unregistered module or a dependency loop is encountered
1113 function sortDependencies( module
, resolved
, unresolved
) {
1116 if ( !hasOwn
.call( registry
, module
) ) {
1117 throw new Error( 'Unknown dependency: ' + module
);
1120 if ( registry
[ module
].skip
!== null ) {
1121 /*jshint evil:true */
1122 skip
= new Function( registry
[ module
].skip
);
1123 registry
[ module
].skip
= null;
1125 registry
[ module
].skipped
= true;
1126 registry
[ module
].dependencies
= [];
1127 registry
[ module
].state
= 'ready';
1128 handlePending( module
);
1133 // Resolves dynamic loader function and replaces it with its own results
1134 if ( typeof registry
[ module
].dependencies
=== 'function' ) {
1135 registry
[ module
].dependencies
= registry
[ module
].dependencies();
1136 // Ensures the module's dependencies are always in an array
1137 if ( typeof registry
[ module
].dependencies
!== 'object' ) {
1138 registry
[ module
].dependencies
= [ registry
[ module
].dependencies
];
1141 if ( $.inArray( module
, resolved
) !== -1 ) {
1142 // Module already resolved; nothing to do
1145 // Create unresolved if not passed in
1146 if ( !unresolved
) {
1149 // Tracks down dependencies
1150 deps
= registry
[ module
].dependencies
;
1151 for ( i
= 0; i
< deps
.length
; i
++ ) {
1152 if ( $.inArray( deps
[ i
], resolved
) === -1 ) {
1153 if ( unresolved
[ deps
[ i
] ] ) {
1154 throw new Error( mw
.format(
1155 'Circular reference detected: $1 -> $2',
1161 // Add to unresolved
1162 unresolved
[ module
] = true;
1163 sortDependencies( deps
[ i
], resolved
, unresolved
);
1166 resolved
.push( module
);
1170 * Get names of module that a module depends on, in their proper dependency order.
1173 * @param {string[]} modules Array of string module names
1174 * @return {Array} List of dependencies, including 'module'.
1176 function resolve( modules
) {
1178 $.each( modules
, function ( idx
, module
) {
1179 sortDependencies( module
, resolved
);
1185 * Load and execute a script.
1188 * @param {string} src URL to script, will be used as the src attribute in the script tag
1189 * @return {jQuery.Promise}
1191 function addScript( src
) {
1195 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1196 // XHR for a same domain request instead of <script>, which changes the request
1197 // headers (potentially missing a cache hit), and reduces caching in general
1198 // since browsers cache XHR much less (if at all). And XHR means we retreive
1199 // text, so we'd need to $.globalEval, which then messes up line numbers.
1206 * Queue the loading and execution of a script for a particular module.
1209 * @param {string} src URL of the script
1210 * @param {string} [moduleName] Name of currently executing module
1211 * @return {jQuery.Promise}
1213 function queueModuleScript( src
, moduleName
) {
1214 var r
= $.Deferred();
1216 pendingRequests
.push( function () {
1217 if ( moduleName
&& hasOwn
.call( registry
, moduleName
) ) {
1218 window
.require
= mw
.loader
.require
;
1219 window
.module
= registry
[ moduleName
].module
;
1221 addScript( src
).always( function () {
1222 // Clear environment
1223 delete window
.require
;
1224 delete window
.module
;
1227 // Start the next one (if any)
1228 if ( pendingRequests
[ 0 ] ) {
1229 pendingRequests
.shift()();
1231 handlingPendingRequests
= false;
1235 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1236 handlingPendingRequests
= true;
1237 pendingRequests
.shift()();
1243 * Utility function for execute()
1247 function addLink( media
, url
) {
1248 var el
= document
.createElement( 'link' );
1250 el
.rel
= 'stylesheet';
1251 if ( media
&& media
!== 'all' ) {
1254 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1255 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1258 $( getMarker() ).before( el
);
1262 * Executes a loaded module, making it ready to use
1265 * @param {string} module Module name to execute
1267 function execute( module
) {
1268 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1269 cssHandlesRegistered
= false;
1271 if ( !hasOwn
.call( registry
, module
) ) {
1272 throw new Error( 'Module has not been registered yet: ' + module
);
1274 if ( registry
[ module
].state
!== 'loaded' ) {
1275 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1278 registry
[ module
].state
= 'executing';
1280 runScript = function () {
1281 var script
, markModuleReady
, nestedAddScript
, legacyWait
,
1282 // Expand to include dependencies since we have to exclude both legacy modules
1283 // and their dependencies from the legacyWait (to prevent a circular dependency).
1284 legacyModules
= resolve( mw
.config
.get( 'wgResourceLoaderLegacyModules', [] ) );
1286 script
= registry
[ module
].script
;
1287 markModuleReady = function () {
1288 registry
[ module
].state
= 'ready';
1289 handlePending( module
);
1291 nestedAddScript = function ( arr
, callback
, i
) {
1292 // Recursively call queueModuleScript() in its own callback
1293 // for each element of arr.
1294 if ( i
>= arr
.length
) {
1295 // We're at the end of the array
1300 queueModuleScript( arr
[ i
], module
).always( function () {
1301 nestedAddScript( arr
, callback
, i
+ 1 );
1305 legacyWait
= ( $.inArray( module
, legacyModules
) !== -1 )
1306 ? $.Deferred().resolve()
1307 : mw
.loader
.using( legacyModules
);
1309 legacyWait
.always( function () {
1310 if ( $.isArray( script
) ) {
1311 nestedAddScript( script
, markModuleReady
, 0 );
1312 } else if ( typeof script
=== 'function' ) {
1313 // Pass jQuery twice so that the signature of the closure which wraps
1314 // the script can bind both '$' and 'jQuery'.
1315 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1318 } else if ( typeof script
=== 'string' ) {
1319 // Site and user modules are legacy scripts that run in the global scope.
1320 // This is transported as a string instead of a function to avoid needing
1321 // to use string manipulation to undo the function wrapper.
1322 if ( module
=== 'user' ) {
1323 // Implicit dependency on the site module. Not real dependency because
1324 // it should run after 'site' regardless of whether it succeeds or fails.
1325 mw
.loader
.using( 'site' ).always( function () {
1326 $.globalEval( script
);
1330 $.globalEval( script
);
1334 // Module without script
1339 // This needs to NOT use mw.log because these errors are common in production mode
1340 // and not in debug mode, such as when a symbol that should be global isn't exported
1341 registry
[ module
].state
= 'error';
1342 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1343 handlePending( module
);
1347 // Add localizations to message system
1348 if ( registry
[ module
].messages
) {
1349 mw
.messages
.set( registry
[ module
].messages
);
1352 // Initialise templates
1353 if ( registry
[ module
].templates
) {
1354 mw
.templates
.set( module
, registry
[ module
].templates
);
1357 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1360 checkCssHandles = function () {
1361 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1362 // one of the cssHandles is fired while we're still creating more handles.
1363 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1365 runScript
= undefined; // Revoke
1368 cssHandle = function () {
1369 var check
= checkCssHandles
;
1371 return function () {
1375 check
= undefined; // Revoke
1381 // Process styles (see also mw.loader.implement)
1382 // * back-compat: { <media>: css }
1383 // * back-compat: { <media>: [url, ..] }
1384 // * { "css": [css, ..] }
1385 // * { "url": { <media>: [url, ..] } }
1386 if ( registry
[ module
].style
) {
1387 for ( key
in registry
[ module
].style
) {
1388 value
= registry
[ module
].style
[ key
];
1391 if ( key
!== 'url' && key
!== 'css' ) {
1392 // Backwards compatibility, key is a media-type
1393 if ( typeof value
=== 'string' ) {
1394 // back-compat: { <media>: css }
1395 // Ignore 'media' because it isn't supported (nor was it used).
1396 // Strings are pre-wrapped in "@media". The media-type was just ""
1397 // (because it had to be set to something).
1398 // This is one of the reasons why this format is no longer used.
1399 addEmbeddedCSS( value
, cssHandle() );
1401 // back-compat: { <media>: [url, ..] }
1407 // Array of css strings in key 'css',
1408 // or back-compat array of urls from media-type
1409 if ( $.isArray( value
) ) {
1410 for ( i
= 0; i
< value
.length
; i
++ ) {
1411 if ( key
=== 'bc-url' ) {
1412 // back-compat: { <media>: [url, ..] }
1413 addLink( media
, value
[ i
] );
1414 } else if ( key
=== 'css' ) {
1415 // { "css": [css, ..] }
1416 addEmbeddedCSS( value
[ i
], cssHandle() );
1419 // Not an array, but a regular object
1420 // Array of urls inside media-type key
1421 } else if ( typeof value
=== 'object' ) {
1422 // { "url": { <media>: [url, ..] } }
1423 for ( media
in value
) {
1424 urls
= value
[ media
];
1425 for ( i
= 0; i
< urls
.length
; i
++ ) {
1426 addLink( media
, urls
[ i
] );
1434 cssHandlesRegistered
= true;
1439 * Add one or more modules to the module load queue.
1444 * @param {string|string[]} dependencies Module name or array of string module names
1445 * @param {Function} [ready] Callback to execute when all dependencies are ready
1446 * @param {Function} [error] Callback to execute when any dependency fails
1448 function enqueue( dependencies
, ready
, error
) {
1449 // Allow calling by single module name
1450 if ( typeof dependencies
=== 'string' ) {
1451 dependencies
= [ dependencies
];
1454 // Add ready and error callbacks if they were given
1455 if ( ready
!== undefined || error
!== undefined ) {
1457 // Narrow down the list to modules that are worth waiting for
1458 dependencies
: $.grep( dependencies
, function ( module
) {
1459 var state
= mw
.loader
.getState( module
);
1460 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1467 $.each( dependencies
, function ( idx
, module
) {
1468 var state
= mw
.loader
.getState( module
);
1469 // Only queue modules that are still in the initial 'registered' state
1470 // (not ones already loading, ready or error).
1471 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1472 // Private modules must be embedded in the page. Don't bother queuing
1473 // these as the server will deny them anyway (T101806).
1474 if ( registry
[ module
].group
=== 'private' ) {
1475 registry
[ module
].state
= 'error';
1476 handlePending( module
);
1479 queue
.push( module
);
1486 function sortQuery( o
) {
1492 if ( hasOwn
.call( o
, key
) ) {
1497 for ( key
= 0; key
< a
.length
; key
++ ) {
1498 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1504 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1505 * to a query string of the form foo.bar,baz|bar.baz,quux
1509 function buildModulesString( moduleMap
) {
1513 for ( prefix
in moduleMap
) {
1514 p
= prefix
=== '' ? '' : prefix
+ '.';
1515 arr
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1517 return arr
.join( '|' );
1521 * Make a network request to load modules from the server.
1524 * @param {Object} moduleMap Module map, see #buildModulesString
1525 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1526 * @param {string} sourceLoadScript URL of load.php
1528 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
1529 var query
= $.extend(
1530 { modules
: buildModulesString( moduleMap
) },
1533 query
= sortQuery( query
);
1534 addScript( sourceLoadScript
+ '?' + $.param( query
) );
1538 * Resolve indexed dependencies.
1540 * ResourceLoader uses an optimization to save space which replaces module names in
1541 * dependency lists with the index of that module within the array of module
1542 * registration data if it exists. The benefit is a significant reduction in the data
1543 * size of the startup module. This function changes those dependency lists back to
1544 * arrays of strings.
1547 * @param {Array} modules Modules array
1549 function resolveIndexedDependencies( modules
) {
1551 function resolveIndex( dep
) {
1552 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1554 for ( i
= 0; i
< modules
.length
; i
++ ) {
1555 deps
= modules
[ i
][ 2 ];
1557 for ( j
= 0; j
< deps
.length
; j
++ ) {
1558 deps
[ j
] = resolveIndex( deps
[ j
] );
1565 * Create network requests for a batch of modules.
1567 * This is an internal method for #work(). This must not be called directly
1568 * unless the modules are already registered, and no request is in progress,
1569 * and the module state has already been set to `loading`.
1572 * @param {string[]} batch
1574 function batchRequest( batch
) {
1575 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1576 source
, group
, i
, modules
, sourceLoadScript
,
1577 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1578 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1580 if ( !batch
.length
) {
1584 // Always order modules alphabetically to help reduce cache
1585 // misses for otherwise identical content.
1588 // Build a list of query parameters common to all requests
1590 skin
: mw
.config
.get( 'skin' ),
1591 lang
: mw
.config
.get( 'wgUserLanguage' ),
1592 debug
: mw
.config
.get( 'debug' )
1594 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1596 // Split module list by source and by group.
1598 for ( b
= 0; b
< batch
.length
; b
++ ) {
1599 bSource
= registry
[ batch
[ b
] ].source
;
1600 bGroup
= registry
[ batch
[ b
] ].group
;
1601 if ( !hasOwn
.call( splits
, bSource
) ) {
1602 splits
[ bSource
] = {};
1604 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1605 splits
[ bSource
][ bGroup
] = [];
1607 bSourceGroup
= splits
[ bSource
][ bGroup
];
1608 bSourceGroup
.push( batch
[ b
] );
1611 for ( source
in splits
) {
1613 sourceLoadScript
= sources
[ source
];
1615 for ( group
in splits
[ source
] ) {
1617 // Cache access to currently selected list of
1618 // modules for this group from this source.
1619 modules
= splits
[ source
][ group
];
1621 currReqBase
= $.extend( {
1622 version
: getCombinedVersion( modules
)
1624 // For user modules append a user name to the query string.
1625 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1626 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1628 currReqBaseLength
= $.param( currReqBase
).length
;
1629 // We may need to split up the request to honor the query string length limit,
1630 // so build it piece by piece.
1631 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1633 moduleMap
= {}; // { prefix: [ suffixes ] }
1635 for ( i
= 0; i
< modules
.length
; i
++ ) {
1636 // Determine how many bytes this module would add to the query string
1637 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1639 // If lastDotIndex is -1, substr() returns an empty string
1640 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1641 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1643 bytesAdded
= hasOwn
.call( moduleMap
, prefix
)
1644 ? suffix
.length
+ 3 // '%2C'.length == 3
1645 : modules
[ i
].length
+ 3; // '%7C'.length == 3
1647 // If the url would become too long, create a new one,
1648 // but don't create empty requests
1649 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1650 // This url would become too long, create a new one, and start the old one
1651 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1653 l
= currReqBaseLength
+ 9;
1654 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1656 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1657 moduleMap
[ prefix
] = [];
1659 moduleMap
[ prefix
].push( suffix
);
1662 // If there's anything left in moduleMap, request that too
1663 if ( !$.isEmptyObject( moduleMap
) ) {
1664 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1670 /* Public Members */
1673 * The module registry is exposed as an aid for debugging and inspecting page
1674 * state; it is not a public interface for modifying the registry.
1680 moduleRegistry
: registry
,
1683 * @inheritdoc #newStyleTag
1686 addStyleTag
: newStyleTag
,
1689 * Start loading of all queued module dependencies.
1694 var q
, batch
, concatSource
, origBatch
;
1698 // Appends a list of modules from the queue to the batch
1699 for ( q
= 0; q
< queue
.length
; q
++ ) {
1700 // Only load modules which are registered
1701 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1702 // Prevent duplicate entries
1703 if ( $.inArray( queue
[ q
], batch
) === -1 ) {
1704 batch
.push( queue
[ q
] );
1705 // Mark registered modules as loading
1706 registry
[ queue
[ q
] ].state
= 'loading';
1711 mw
.loader
.store
.init();
1712 if ( mw
.loader
.store
.enabled
) {
1715 batch
= $.grep( batch
, function ( module
) {
1716 var source
= mw
.loader
.store
.get( module
);
1718 concatSource
.push( source
);
1724 $.globalEval( concatSource
.join( ';' ) );
1726 // Not good, the cached mw.loader.implement calls failed! This should
1727 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1728 // Depending on how corrupt the string is, it is likely that some
1729 // modules' implement() succeeded while the ones after the error will
1730 // never run and leave their modules in the 'loading' state forever.
1732 // Since this is an error not caused by an individual module but by
1733 // something that infected the implement call itself, don't take any
1734 // risks and clear everything in this cache.
1735 mw
.loader
.store
.clear();
1736 // Re-add the ones still pending back to the batch and let the server
1737 // repopulate these modules to the cache.
1738 // This means that at most one module will be useless (the one that had
1739 // the error) instead of all of them.
1740 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1741 origBatch
= $.grep( origBatch
, function ( module
) {
1742 return registry
[ module
].state
=== 'loading';
1744 batch
= batch
.concat( origBatch
);
1748 // Now that the queue has been processed into a batch, clear up the queue.
1749 // This MUST happen before we initiate any network request. Else it's possible
1750 // that a script will be locally cached, instantly load, and work the queue
1751 // again; all before we've cleared it causing each request to include modules
1752 // which are already loaded.
1755 batchRequest( batch
);
1759 * Register a source.
1761 * The #work() method will use this information to split up requests by source.
1763 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1765 * @param {string|Object} id Source ID, or object mapping ids to load urls
1766 * @param {string} loadUrl Url to a load.php end point
1767 * @throws {Error} If source id is already registered
1769 addSource: function ( id
, loadUrl
) {
1771 // Allow multiple additions
1772 if ( typeof id
=== 'object' ) {
1773 for ( source
in id
) {
1774 mw
.loader
.addSource( source
, id
[ source
] );
1779 if ( hasOwn
.call( sources
, id
) ) {
1780 throw new Error( 'source already registered: ' + id
);
1783 sources
[ id
] = loadUrl
;
1787 * Register a module, letting the system know about it and its properties.
1789 * The startup modules contain calls to this method.
1791 * When using multiple module registration by passing an array, dependencies that
1792 * are specified as references to modules within the array will be resolved before
1793 * the modules are registered.
1795 * @param {string|Array} module Module name or array of arrays, each containing
1796 * a list of arguments compatible with this method
1797 * @param {string|number} version Module version hash (falls backs to empty string)
1798 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1799 * @param {string|Array|Function} dependencies One string or array of strings of module
1800 * names on which this module depends, or a function that returns that array.
1801 * @param {string} [group=null] Group which the module is in
1802 * @param {string} [source='local'] Name of the source
1803 * @param {string} [skip=null] Script body of the skip function
1805 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1807 // Allow multiple registration
1808 if ( typeof module
=== 'object' ) {
1809 resolveIndexedDependencies( module
);
1810 for ( i
= 0; i
< module
.length
; i
++ ) {
1811 // module is an array of module names
1812 if ( typeof module
[ i
] === 'string' ) {
1813 mw
.loader
.register( module
[ i
] );
1814 // module is an array of arrays
1815 } else if ( typeof module
[ i
] === 'object' ) {
1816 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1821 if ( hasOwn
.call( registry
, module
) ) {
1822 throw new Error( 'module already registered: ' + module
);
1824 if ( typeof dependencies
=== 'string' ) {
1825 // A single module name
1826 deps
= [ dependencies
];
1827 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
1828 // Array of module names or a function that returns an array
1829 deps
= dependencies
;
1831 // List the module as registered
1832 registry
[ module
] = {
1833 // Exposed to execute() for mw.loader.implement() closures.
1834 // Import happens via require().
1838 version
: version
!== undefined ? String( version
) : '',
1839 dependencies
: deps
|| [],
1840 group
: typeof group
=== 'string' ? group
: null,
1841 source
: typeof source
=== 'string' ? source
: 'local',
1842 state
: 'registered',
1843 skip
: typeof skip
=== 'string' ? skip
: null
1848 * Implement a module given the components that make up the module.
1850 * When #load() or #using() requests one or more modules, the server
1851 * response contain calls to this function.
1853 * @param {string} module Name of module
1854 * @param {Function|Array} [script] Function with module code or Array of URLs to
1855 * be used as the src attribute of a new `<script>` tag.
1856 * @param {Object} [style] Should follow one of the following patterns:
1858 * { "css": [css, ..] }
1859 * { "url": { <media>: [url, ..] } }
1861 * And for backwards compatibility (needs to be supported forever due to caching):
1864 * { <media>: [url, ..] }
1866 * The reason css strings are not concatenated anymore is bug 31676. We now check
1867 * whether it's safe to extend the stylesheet.
1870 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1871 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1873 implement: function ( module
, script
, style
, messages
, templates
) {
1874 // Automatically register module
1875 if ( !hasOwn
.call( registry
, module
) ) {
1876 mw
.loader
.register( module
);
1878 // Check for duplicate implementation
1879 if ( hasOwn
.call( registry
, module
) && registry
[ module
].script
!== undefined ) {
1880 throw new Error( 'module already implemented: ' + module
);
1882 // Attach components
1883 registry
[ module
].script
= script
|| null;
1884 registry
[ module
].style
= style
|| null;
1885 registry
[ module
].messages
= messages
|| null;
1886 registry
[ module
].templates
= templates
|| null;
1887 // The module may already have been marked as erroneous
1888 if ( $.inArray( registry
[ module
].state
, [ 'error', 'missing' ] ) === -1 ) {
1889 registry
[ module
].state
= 'loaded';
1890 if ( allReady( registry
[ module
].dependencies
) ) {
1897 * Execute a function as soon as one or more required modules are ready.
1899 * Example of inline dependency on OOjs:
1901 * mw.loader.using( 'oojs', function () {
1902 * OO.compare( [ 1 ], [ 1 ] );
1905 * Since MediaWiki 1.23 this also returns a promise.
1907 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1909 * @param {string|Array} dependencies Module name or array of modules names the
1910 * callback depends on to be ready before executing
1911 * @param {Function} [ready] Callback to execute when all dependencies are ready
1912 * @param {Function} [error] Callback to execute if one or more dependencies failed
1913 * @return {jQuery.Promise} With a `require` function
1915 using: function ( dependencies
, ready
, error
) {
1916 var deferred
= $.Deferred();
1918 // Allow calling with a single dependency as a string
1919 if ( typeof dependencies
=== 'string' ) {
1920 dependencies
= [ dependencies
];
1924 deferred
.done( ready
);
1927 deferred
.fail( error
);
1930 // Resolve entire dependency map
1931 dependencies
= resolve( dependencies
);
1932 if ( allReady( dependencies
) ) {
1933 // Run ready immediately
1934 deferred
.resolve( mw
.loader
.require
);
1935 } else if ( anyFailed( dependencies
) ) {
1936 // Execute error immediately if any dependencies have errors
1938 new Error( 'One or more dependencies failed to load' ),
1942 // Not all dependencies are ready, add to the load queue
1943 enqueue( dependencies
, function () {
1944 deferred
.resolve( mw
.loader
.require
);
1945 }, deferred
.reject
);
1948 return deferred
.promise();
1952 * Load an external script or one or more modules.
1954 * @param {string|Array} modules Either the name of a module, array of modules,
1955 * or a URL of an external script or style
1956 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1957 * external script or style; acceptable values are "text/css" and
1958 * "text/javascript"; if no type is provided, text/javascript is assumed.
1960 load: function ( modules
, type
) {
1963 // Allow calling with a url or single dependency as a string
1964 if ( typeof modules
=== 'string' ) {
1965 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1966 if ( /^(https?:)?\/?\//.test( modules
) ) {
1967 if ( type
=== 'text/css' ) {
1969 // Use properties instead of attributes as IE throws security
1970 // warnings when inserting a <link> tag with a protocol-relative
1971 // URL set though attributes - when on HTTPS. See bug 41331.
1972 l
= document
.createElement( 'link' );
1973 l
.rel
= 'stylesheet';
1975 $( 'head' ).append( l
);
1978 if ( type
=== 'text/javascript' || type
=== undefined ) {
1979 addScript( modules
);
1983 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1985 // Called with single module
1986 modules
= [ modules
];
1989 // Filter out undefined modules, otherwise resolve() will throw
1990 // an exception for trying to load an undefined module.
1991 // Undefined modules are acceptable here in load(), because load() takes
1992 // an array of unrelated modules, whereas the modules passed to
1993 // using() are related and must all be loaded.
1994 filtered
= $.grep( modules
, function ( module
) {
1995 var state
= mw
.loader
.getState( module
);
1996 return state
!== null && state
!== 'error' && state
!== 'missing';
1999 if ( filtered
.length
=== 0 ) {
2002 // Resolve entire dependency map
2003 filtered
= resolve( filtered
);
2004 // If all modules are ready, or if any modules have errors, nothing to be done.
2005 if ( allReady( filtered
) || anyFailed( filtered
) ) {
2008 // Some modules are not yet ready, add to module load queue.
2009 enqueue( filtered
, undefined, undefined );
2013 * Change the state of one or more modules.
2015 * @param {string|Object} module Module name or object of module name/state pairs
2016 * @param {string} state State name
2018 state: function ( module
, state
) {
2021 if ( typeof module
=== 'object' ) {
2022 for ( m
in module
) {
2023 mw
.loader
.state( m
, module
[ m
] );
2027 if ( !hasOwn
.call( registry
, module
) ) {
2028 mw
.loader
.register( module
);
2030 registry
[ module
].state
= state
;
2031 if ( $.inArray( state
, [ 'ready', 'error', 'missing' ] ) !== -1 ) {
2032 // Make sure pending modules depending on this one get executed if their
2033 // dependencies are now fulfilled!
2034 handlePending( module
);
2039 * Get the version of a module.
2041 * @param {string} module Name of module
2042 * @return {string|null} The version, or null if the module (or its version) is not
2045 getVersion: function ( module
) {
2046 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].version
=== undefined ) {
2049 return registry
[ module
].version
;
2053 * Get the state of a module.
2055 * @param {string} module Name of module
2056 * @return {string|null} The state, or null if the module (or its state) is not
2059 getState: function ( module
) {
2060 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].state
=== undefined ) {
2063 return registry
[ module
].state
;
2067 * Get the names of all registered modules.
2071 getModuleNames: function () {
2072 return $.map( registry
, function ( i
, key
) {
2078 * Get the exported value of a module.
2080 * Modules may provide this via their local `module.exports`.
2085 require: function ( moduleName
) {
2086 var state
= mw
.loader
.getState( moduleName
);
2088 // Only ready modules can be required
2089 if ( state
!== 'ready' ) {
2090 // Module may've forgotten to declare a dependency
2091 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2094 return registry
[ moduleName
].module
.exports
;
2098 * @inheritdoc mw.inspect#runReports
2101 inspect: function () {
2102 var args
= slice
.call( arguments
);
2103 mw
.loader
.using( 'mediawiki.inspect', function () {
2104 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2109 * On browsers that implement the localStorage API, the module store serves as a
2110 * smart complement to the browser cache. Unlike the browser cache, the module store
2111 * can slice a concatenated response from ResourceLoader into its constituent
2112 * modules and cache each of them separately, using each module's versioning scheme
2113 * to determine when the cache should be invalidated.
2116 * @class mw.loader.store
2119 // Whether the store is in use on this page.
2122 MODULE_SIZE_MAX
: 100 * 1000,
2124 // The contents of the store, mapping '[module name]@[version]' keys
2125 // to module implementations.
2129 stats
: { hits
: 0, misses
: 0, expired
: 0 },
2132 * Construct a JSON-serializable object representing the content of the store.
2134 * @return {Object} Module store contents.
2136 toJSON: function () {
2137 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2141 * Get the localStorage key for the entire module store. The key references
2142 * $wgDBname to prevent clashes between wikis which share a common host.
2144 * @return {string} localStorage item key
2146 getStoreKey: function () {
2147 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2151 * Get a key on which to vary the module cache.
2153 * @return {string} String of concatenated vary conditions.
2155 getVary: function () {
2157 mw
.config
.get( 'skin' ),
2158 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2159 mw
.config
.get( 'wgUserLanguage' )
2164 * Get a key for a specific module. The key format is '[name]@[version]'.
2166 * @param {string} module Module name
2167 * @return {string|null} Module key or null if module does not exist
2169 getModuleKey: function ( module
) {
2170 return hasOwn
.call( registry
, module
) ?
2171 ( module
+ '@' + registry
[ module
].version
) : null;
2175 * Initialize the store.
2177 * Retrieves store from localStorage and (if successfully retrieved) decoding
2178 * the stored JSON value to a plain object.
2180 * The try / catch block is used for JSON & localStorage feature detection.
2181 * See the in-line documentation for Modernizr's localStorage feature detection
2182 * code for a full account of why we need a try / catch:
2183 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2188 if ( mw
.loader
.store
.enabled
!== null ) {
2194 // Disabled because localStorage quotas are tight and (in Firefox's case)
2195 // shared by multiple origins.
2196 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2197 /Firefox|Opera/.test( navigator
.userAgent
) ||
2199 // Disabled by configuration.
2200 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2202 // Clear any previous store to free up space. (T66721)
2203 mw
.loader
.store
.clear();
2204 mw
.loader
.store
.enabled
= false;
2207 if ( mw
.config
.get( 'debug' ) ) {
2208 // Disable module store in debug mode
2209 mw
.loader
.store
.enabled
= false;
2214 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2215 // If we get here, localStorage is available; mark enabled
2216 mw
.loader
.store
.enabled
= true;
2217 data
= JSON
.parse( raw
);
2218 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2219 mw
.loader
.store
.items
= data
.items
;
2223 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2226 if ( raw
=== undefined ) {
2227 // localStorage failed; disable store
2228 mw
.loader
.store
.enabled
= false;
2230 mw
.loader
.store
.update();
2235 * Retrieve a module from the store and update cache hit stats.
2237 * @param {string} module Module name
2238 * @return {string|boolean} Module implementation or false if unavailable
2240 get: function ( module
) {
2243 if ( !mw
.loader
.store
.enabled
) {
2247 key
= mw
.loader
.store
.getModuleKey( module
);
2248 if ( key
in mw
.loader
.store
.items
) {
2249 mw
.loader
.store
.stats
.hits
++;
2250 return mw
.loader
.store
.items
[ key
];
2252 mw
.loader
.store
.stats
.misses
++;
2257 * Stringify a module and queue it for storage.
2259 * @param {string} module Module name
2260 * @param {Object} descriptor The module's descriptor as set in the registry
2262 set: function ( module
, descriptor
) {
2265 if ( !mw
.loader
.store
.enabled
) {
2269 key
= mw
.loader
.store
.getModuleKey( module
);
2272 // Already stored a copy of this exact version
2273 key
in mw
.loader
.store
.items
||
2274 // Module failed to load
2275 descriptor
.state
!== 'ready' ||
2276 // Unversioned, private, or site-/user-specific
2277 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user' ] ) !== -1 ) ||
2278 // Partial descriptor
2279 // (e.g. skipped module, or style module with state=ready)
2280 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2281 descriptor
.messages
, descriptor
.templates
] ) !== -1
2289 JSON
.stringify( module
),
2290 typeof descriptor
.script
=== 'function' ?
2291 String( descriptor
.script
) :
2292 JSON
.stringify( descriptor
.script
),
2293 JSON
.stringify( descriptor
.style
),
2294 JSON
.stringify( descriptor
.messages
),
2295 JSON
.stringify( descriptor
.templates
)
2297 // Attempted workaround for a possible Opera bug (bug T59567).
2298 // This regex should never match under sane conditions.
2299 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2300 args
[ 1 ] = 'function' + args
[ 1 ];
2301 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2304 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2308 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2309 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2312 mw
.loader
.store
.items
[ key
] = src
;
2313 mw
.loader
.store
.update();
2317 * Iterate through the module store, removing any item that does not correspond
2318 * (in name and version) to an item in the module registry.
2320 prune: function () {
2323 if ( !mw
.loader
.store
.enabled
) {
2327 for ( key
in mw
.loader
.store
.items
) {
2328 module
= key
.slice( 0, key
.indexOf( '@' ) );
2329 if ( mw
.loader
.store
.getModuleKey( module
) !== key
) {
2330 mw
.loader
.store
.stats
.expired
++;
2331 delete mw
.loader
.store
.items
[ key
];
2332 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2333 // This value predates the enforcement of a size limit on cached modules.
2334 delete mw
.loader
.store
.items
[ key
];
2340 * Clear the entire module store right now.
2342 clear: function () {
2343 mw
.loader
.store
.items
= {};
2345 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2346 } catch ( ignored
) {}
2350 * Sync in-memory store back to localStorage.
2352 * This function debounces updates. When called with a flush already pending,
2353 * the call is coalesced into the pending update. The call to
2354 * localStorage.setItem will be naturally deferred until the page is quiescent.
2356 * Because localStorage is shared by all pages from the same origin, if multiple
2357 * pages are loaded with different module sets, the possibility exists that
2358 * modules saved by one page will be clobbered by another. But the impact would
2359 * be minor and the problem would be corrected by subsequent page views.
2363 update
: ( function () {
2364 var hasPendingWrite
= false;
2366 function flushWrites() {
2368 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2372 mw
.loader
.store
.prune();
2373 key
= mw
.loader
.store
.getStoreKey();
2375 // Replacing the content of the module store might fail if the new
2376 // contents would exceed the browser's localStorage size limit. To
2377 // avoid clogging the browser with stale data, always remove the old
2378 // value before attempting to set the new one.
2379 localStorage
.removeItem( key
);
2380 data
= JSON
.stringify( mw
.loader
.store
);
2381 localStorage
.setItem( key
, data
);
2383 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2386 hasPendingWrite
= false;
2389 return function () {
2390 if ( !hasPendingWrite
) {
2391 hasPendingWrite
= true;
2392 mw
.requestIdleCallback( flushWrites
);
2401 * HTML construction helper functions
2408 * output = Html.element( 'div', {}, new Html.Raw(
2409 * Html.element( 'img', { src: '<' } )
2411 * mw.log( output ); // <div><img src="<"/></div>
2416 html
: ( function () {
2417 function escapeCallback( s
) {
2434 * Escape a string for HTML.
2436 * Converts special characters to HTML entities.
2438 * mw.html.escape( '< > \' & "' );
2439 * // Returns < > ' & "
2441 * @param {string} s The string to escape
2442 * @return {string} HTML
2444 escape: function ( s
) {
2445 return s
.replace( /['"<>&]/g, escapeCallback
);
2449 * Create an HTML element string, with safe escaping.
2451 * @param {string} name The tag name.
2452 * @param {Object} [attrs] An object with members mapping element names to values
2453 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2455 * - string: Text to be escaped.
2456 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2457 * - this.Raw: The raw value is directly included.
2458 * - this.Cdata: The raw value is directly included. An exception is
2459 * thrown if it contains any illegal ETAGO delimiter.
2460 * See <http://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2461 * @return {string} HTML
2463 element: function ( name
, attrs
, contents
) {
2464 var v
, attrName
, s
= '<' + name
;
2467 for ( attrName
in attrs
) {
2468 v
= attrs
[ attrName
];
2469 // Convert name=true, to name=name
2473 } else if ( v
=== false ) {
2476 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2479 if ( contents
=== undefined || contents
=== null ) {
2486 switch ( typeof contents
) {
2489 s
+= this.escape( contents
);
2493 // Convert to string
2494 s
+= String( contents
);
2497 if ( contents
instanceof this.Raw
) {
2498 // Raw HTML inclusion
2499 s
+= contents
.value
;
2500 } else if ( contents
instanceof this.Cdata
) {
2502 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2503 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2505 s
+= contents
.value
;
2507 throw new Error( 'mw.html.element: Invalid type of contents' );
2510 s
+= '</' + name
+ '>';
2515 * Wrapper object for raw HTML passed to mw.html.element().
2517 * @class mw.html.Raw
2519 Raw: function ( value
) {
2524 * Wrapper object for CDATA element contents passed to mw.html.element()
2526 * @class mw.html.Cdata
2528 Cdata: function ( value
) {
2534 // Skeleton user object, extended by the 'mediawiki.user' module.
2541 * @property {mw.Map}
2545 * @property {mw.Map}
2550 // OOUI widgets specific to MediaWiki
2554 * Registry and firing of events.
2556 * MediaWiki has various interface components that are extended, enhanced
2557 * or manipulated in some other way by extensions, gadgets and even
2560 * This framework helps streamlining the timing of when these other
2561 * code paths fire their plugins (instead of using document-ready,
2562 * which can and should be limited to firing only once).
2564 * Features like navigating to other wiki pages, previewing an edit
2565 * and editing itself – without a refresh – can then retrigger these
2566 * hooks accordingly to ensure everything still works as expected.
2570 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2571 * mw.hook( 'wikipage.content' ).fire( $content );
2573 * Handlers can be added and fired for arbitrary event names at any time. The same
2574 * event can be fired multiple times. The last run of an event is memorized
2575 * (similar to `$(document).ready` and `$.Deferred().done`).
2576 * This means if an event is fired, and a handler added afterwards, the added
2577 * function will be fired right away with the last given event data.
2579 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2580 * Thus allowing flexible use and optimal maintainability and authority control.
2581 * You can pass around the `add` and/or `fire` method to another piece of code
2582 * without it having to know the event name (or `mw.hook` for that matter).
2584 * var h = mw.hook( 'bar.ready' );
2585 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2587 * Note: Events are documented with an underscore instead of a dot in the event
2588 * name due to jsduck not supporting dots in that position.
2592 hook
: ( function () {
2596 * Create an instance of mw.hook.
2600 * @param {string} name Name of hook.
2603 return function ( name
) {
2604 var list
= hasOwn
.call( lists
, name
) ?
2606 lists
[ name
] = $.Callbacks( 'memory' );
2610 * Register a hook handler
2612 * @param {...Function} handler Function to bind.
2618 * Unregister a hook handler
2620 * @param {...Function} handler Function to unbind.
2623 remove
: list
.remove
,
2628 * @param {...Mixed} data
2632 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2639 // Alias $j to jQuery for backwards compatibility
2640 // @deprecated since 1.23 Use $ or jQuery instead
2641 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2644 * Log a message to window.console, if possible.
2646 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2647 * also in production mode). Gets console references in each invocation instead of caching the
2648 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2652 * @param {string} topic Stream name passed by mw.track
2653 * @param {Object} data Data passed by mw.track
2654 * @param {Error} [data.exception]
2655 * @param {string} data.source Error source
2656 * @param {string} [data.module] Name of module which caused the error
2658 function log( topic
, data
) {
2661 source
= data
.source
,
2662 module
= data
.module
,
2663 console
= window
.console
;
2665 if ( console
&& console
.log
) {
2666 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2668 msg
+= ' in module ' + module
;
2670 msg
+= ( e
? ':' : '.' );
2673 // If we have an exception object, log it to the error channel to trigger
2674 // proper stacktraces in browsers that support it. No fallback as we have
2675 // no browsers that don't support error(), but do support log().
2676 if ( e
&& console
.error
) {
2677 console
.error( String( e
), e
);
2682 // Subscribe to error streams
2683 mw
.trackSubscribe( 'resourceloader.exception', log
);
2684 mw
.trackSubscribe( 'resourceloader.assert', log
);
2687 * Fired when all modules associated with the page have finished loading.
2689 * @event resourceloader_loadEnd
2693 var loading
= $.grep( mw
.loader
.getModuleNames(), function ( module
) {
2694 return mw
.loader
.getState( module
) === 'loading';
2696 // In order to use jQuery.when (which stops early if one of the promises got rejected)
2697 // cast any loading failures into successes. We only need a callback, not the module.
2698 loading
= $.map( loading
, function ( module
) {
2699 return mw
.loader
.using( module
).then( null, function () {
2700 return $.Deferred().resolve();
2703 $.when
.apply( $, loading
).then( function () {
2704 mwPerformance
.mark( 'mwLoadEnd' );
2705 mw
.hook( 'resourceloader.loadEnd' ).fire();
2709 // Attach to window and globally alias
2710 window
.mw
= window
.mediaWiki
= mw
;