2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
12 /* eslint-disable no-use-before-define */
17 var mw
, StringSet
, log
,
18 hasOwn
= Object
.prototype.hasOwnProperty
,
19 slice
= Array
.prototype.slice
,
20 trackCallbacks
= $.Callbacks( 'memory' ),
25 * FNV132 hash function
27 * This function implements the 32-bit version of FNV-1.
28 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
29 * its output is base 36 rather than hex.
30 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
33 * @param {string} str String to hash
34 * @return {string} hash as an seven-character base 36 string
36 function fnv132( str
) {
37 /* eslint-disable no-bitwise */
38 var hash
= 0x811C9DC5,
41 for ( i
= 0; i
< str
.length
; i
++ ) {
42 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
43 hash
^= str
.charCodeAt( i
);
46 hash
= ( hash
>>> 0 ).toString( 36 );
47 while ( hash
.length
< 7 ) {
52 /* eslint-enable no-bitwise */
55 function defineFallbacks() {
56 // <https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set>
57 StringSet
= window
.Set
|| ( function () {
62 function StringSet() {
65 StringSet
.prototype.add = function ( value
) {
66 this.set[ value
] = true;
68 StringSet
.prototype.has = function ( value
) {
69 return hasOwn
.call( this.set, value
);
76 * Create an object that can be read from or written to via methods that allow
77 * interaction both with single and multiple properties at once.
83 * @param {boolean} [global=false] Whether to synchronise =values to the global
84 * window object (for backwards-compatibility with mw.config; T72470). Values are
85 * copied in one direction only. Changes to globals do not reflect in the map.
87 function Map( global
) {
89 if ( global
=== true ) {
90 // Override #set to also set the global variable
91 this.set = function ( selection
, value
) {
94 if ( $.isPlainObject( selection
) ) {
95 for ( s
in selection
) {
96 setGlobalMapValue( this, s
, selection
[ s
] );
100 if ( typeof selection
=== 'string' && arguments
.length
) {
101 setGlobalMapValue( this, selection
, value
);
110 * Alias property to the global object.
114 * @param {mw.Map} map
115 * @param {string} key
116 * @param {Mixed} value
118 function setGlobalMapValue( map
, key
, value
) {
119 map
.values
[ key
] = value
;
124 // Deprecation notice for mw.config globals (T58550, T72470)
125 map
=== mw
.config
&& 'Use mw.config instead.'
133 * Get the value of one or more keys.
135 * If called with no arguments, all values are returned.
137 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
138 * @param {Mixed} [fallback=null] Value for keys that don't exist.
139 * @return {Mixed|Object|null} If selection was a string, returns the value,
140 * If selection was an array, returns an object of key/values.
141 * If no selection is passed, a new object with all key/values is returned.
143 get: function ( selection
, fallback
) {
145 fallback
= arguments
.length
> 1 ? fallback
: null;
147 if ( $.isArray( selection
) ) {
149 for ( i
= 0; i
< selection
.length
; i
++ ) {
150 if ( typeof selection
[ i
] === 'string' ) {
151 results
[ selection
[ i
] ] = hasOwn
.call( this.values
, selection
[ i
] ) ?
152 this.values
[ selection
[ i
] ] :
159 if ( typeof selection
=== 'string' ) {
160 return hasOwn
.call( this.values
, selection
) ?
161 this.values
[ selection
] :
165 if ( selection
=== undefined ) {
167 for ( i
in this.values
) {
168 results
[ i
] = this.values
[ i
];
173 // Invalid selection key
178 * Set one or more key/value pairs.
180 * @param {string|Object} selection Key to set value for, or object mapping keys to values
181 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
182 * @return {boolean} True on success, false on failure
184 set: function ( selection
, value
) {
187 if ( $.isPlainObject( selection
) ) {
188 for ( s
in selection
) {
189 this.values
[ s
] = selection
[ s
];
193 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
194 this.values
[ selection
] = value
;
201 * Check if one or more keys exist.
203 * @param {Mixed} selection Key or array of keys to check
204 * @return {boolean} True if the key(s) exist
206 exists: function ( selection
) {
208 if ( $.isArray( selection
) ) {
209 for ( i
= 0; i
< selection
.length
; i
++ ) {
210 if ( typeof selection
[ i
] !== 'string' || !hasOwn
.call( this.values
, selection
[ i
] ) ) {
216 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
221 * Object constructor for messages.
223 * Similar to the Message class in MediaWiki PHP.
225 * Format defaults to 'text'.
231 * 'hello': 'Hello world',
232 * 'hello-user': 'Hello, $1!',
233 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
236 * obj = new mw.Message( mw.messages, 'hello' );
237 * mw.log( obj.text() );
240 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
241 * mw.log( obj.text() );
242 * // Hello, John Doe!
244 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
245 * mw.log( obj.text() );
246 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
248 * // Using mw.message shortcut
249 * obj = mw.message( 'hello-user', 'John Doe' );
250 * mw.log( obj.text() );
251 * // Hello, John Doe!
253 * // Using mw.msg shortcut
254 * str = mw.msg( 'hello-user', 'John Doe' );
256 * // Hello, John Doe!
258 * // Different formats
259 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
261 * obj.format = 'text';
262 * str = obj.toString();
267 * // Hello, John "Wiki" <3 Doe!
269 * mw.log( obj.escaped() );
270 * // Hello, John "Wiki" <3 Doe!
275 * @param {mw.Map} map Message store
276 * @param {string} key
277 * @param {Array} [parameters]
279 function Message( map
, key
, parameters
) {
280 this.format
= 'text';
283 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
287 Message
.prototype = {
289 * Get parsed contents of the message.
291 * The default parser does simple $N replacements and nothing else.
292 * This may be overridden to provide a more complex message parser.
293 * The primary override is in the mediawiki.jqueryMsg module.
295 * This function will not be called for nonexistent messages.
297 * @return {string} Parsed message
299 parser: function () {
300 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
303 // eslint-disable-next-line valid-jsdoc
305 * Add (does not replace) parameters for `$N` placeholder values.
307 * @param {Array} parameters
310 params: function ( parameters
) {
312 for ( i
= 0; i
< parameters
.length
; i
++ ) {
313 this.parameters
.push( parameters
[ i
] );
319 * Convert message object to its string form based on current format.
321 * @return {string} Message as a string in the current form, or `<key>` if key
324 toString: function () {
327 if ( !this.exists() ) {
328 // Use ⧼key⧽ as text if key does not exist
329 // Err on the side of safety, ensure that the output
330 // is always html safe in the event the message key is
331 // missing, since in that case its highly likely the
332 // message key is user-controlled.
333 // '⧼' is used instead of '<' to side-step any
334 // double-escaping issues.
335 // (Keep synchronised with Message::toString() in PHP.)
336 return '⧼' + mw
.html
.escape( this.key
) + '⧽';
339 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
340 text
= this.parser();
343 if ( this.format
=== 'escaped' ) {
344 text
= this.parser();
345 text
= mw
.html
.escape( text
);
352 * Change format to 'parse' and convert message to string
354 * If jqueryMsg is loaded, this parses the message text from wikitext
355 * (where supported) to HTML
357 * Otherwise, it is equivalent to plain.
359 * @return {string} String form of parsed message
362 this.format
= 'parse';
363 return this.toString();
367 * Change format to 'plain' and convert message to string
369 * This substitutes parameters, but otherwise does not change the
372 * @return {string} String form of plain message
375 this.format
= 'plain';
376 return this.toString();
380 * Change format to 'text' and convert message to string
382 * If jqueryMsg is loaded, {{-transformation is done where supported
383 * (such as {{plural:}}, {{gender:}}, {{int:}}).
385 * Otherwise, it is equivalent to plain
387 * @return {string} String form of text message
390 this.format
= 'text';
391 return this.toString();
395 * Change the format to 'escaped' and convert message to string
397 * This is equivalent to using the 'text' format (see #text), then
398 * HTML-escaping the output.
400 * @return {string} String form of html escaped message
402 escaped: function () {
403 this.format
= 'escaped';
404 return this.toString();
408 * Check if a message exists
413 exists: function () {
414 return this.map
.exists( this.key
);
420 /* eslint-disable no-console */
421 log
= ( function () {
422 // Also update the restoration of methods in mediawiki.log.js
423 // when adding or removing methods here.
424 var log = function () {},
425 console
= window
.console
;
433 * Write a message to the console's warning channel.
434 * Actions not supported by the browser console are silently ignored.
436 * @param {...string} msg Messages to output to console
438 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
439 Function
.prototype.bind
.call( console
.warn
, console
) :
443 * Write a message to the console's error channel.
445 * Most browsers provide a stacktrace by default if the argument
446 * is a caught Error object.
449 * @param {Error|...string} msg Messages to output to console
451 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
452 Function
.prototype.bind
.call( console
.error
, console
) :
456 * Create a property in a host object that, when accessed, will produce
457 * a deprecation warning in the console.
459 * @param {Object} obj Host object of deprecated property
460 * @param {string} key Name of property to create in `obj`
461 * @param {Mixed} val The value this property should return when accessed
462 * @param {string} [msg] Optional text to include in the deprecation message
463 * @param {string} [logName=key] Optional custom name for the feature.
464 * This is used instead of `key` in the message and `mw.deprecate` tracking.
466 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
468 } : function ( obj
, key
, val
, msg
, logName
) {
469 var logged
= new StringSet();
470 logName
= logName
|| key
;
471 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
472 function uniqueTrace() {
473 var trace
= new Error().stack
;
474 if ( logged
.has( trace
) ) {
480 // Support: Safari 5.0
481 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
482 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
484 Object
.defineProperty( obj
, key
, {
488 if ( uniqueTrace() ) {
489 mw
.track( 'mw.deprecate', logName
);
494 set: function ( newVal
) {
495 if ( uniqueTrace() ) {
496 mw
.track( 'mw.deprecate', logName
);
509 /* eslint-enable no-console */
515 redefineFallbacksForTest: function () {
516 if ( !window
.QUnit
) {
517 throw new Error( 'Reset not allowed outside unit tests' );
523 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
525 * On browsers that implement the Navigation Timing API, this function will produce floating-point
526 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
527 * it will fall back to using `Date`.
529 * @return {number} Current time
532 // mwNow is defined in startup.js
535 * Format a string. Replace $1, $2 ... $N with positional arguments.
537 * Used by Message#parser().
540 * @param {string} formatString Format string
541 * @param {...Mixed} parameters Values for $N replacements
542 * @return {string} Formatted string
544 format: function ( formatString
) {
545 var parameters
= slice
.call( arguments
, 1 );
546 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
547 var index
= parseInt( match
, 10 ) - 1;
548 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
553 * Track an analytic event.
555 * This method provides a generic means for MediaWiki JavaScript code to capture state
556 * information for analysis. Each logged event specifies a string topic name that describes
557 * the kind of event that it is. Topic names consist of dot-separated path components,
558 * arranged from most general to most specific. Each path component should have a clear and
559 * well-defined purpose.
561 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
562 * events that match their subcription, including those that fired before the handler was
565 * @param {string} topic Topic name
566 * @param {Object} [data] Data describing the event, encoded as an object
568 track: function ( topic
, data
) {
569 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
570 trackCallbacks
.fire( trackQueue
);
574 * Register a handler for subset of analytic events, specified by topic.
576 * Handlers will be called once for each tracked event, including any events that fired before the
577 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
578 * the exact time at which the event fired, a string 'topic' property naming the event, and a
579 * 'data' property which is an object of event-specific data. The event topic and event data are
580 * also passed to the callback as the first and second arguments, respectively.
582 * @param {string} topic Handle events whose name starts with this string prefix
583 * @param {Function} callback Handler to call for each matching tracked event
584 * @param {string} callback.topic
585 * @param {Object} [callback.data]
587 trackSubscribe: function ( topic
, callback
) {
589 function handler( trackQueue
) {
591 for ( ; seen
< trackQueue
.length
; seen
++ ) {
592 event
= trackQueue
[ seen
];
593 if ( event
.topic
.indexOf( topic
) === 0 ) {
594 callback
.call( event
, event
.topic
, event
.data
);
599 trackHandlers
.push( [ handler
, callback
] );
601 trackCallbacks
.add( handler
);
605 * Stop handling events for a particular handler
607 * @param {Function} callback
609 trackUnsubscribe: function ( callback
) {
610 trackHandlers
= $.grep( trackHandlers
, function ( fns
) {
611 if ( fns
[ 1 ] === callback
) {
612 trackCallbacks
.remove( fns
[ 0 ] );
613 // Ensure the tuple is removed to avoid holding on to closures
620 // Expose Map constructor
623 // Expose Message constructor
627 * Map of configuration values.
629 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
632 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
633 * global `window` object.
635 * @property {mw.Map} config
637 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
641 * Empty object for third-party libraries, for cases where you don't
642 * want to add a new global, or the global is bad and needs containment
650 * Access container for deprecated functionality that can be moved from
651 * from their legacy location and attached to this object (e.g. a global
652 * function that is deprecated and as stop-gap can be exposed through here).
654 * This was reserved for future use but never ended up being used.
656 * @deprecated since 1.22 Let deprecated identifiers keep their original name
657 * and use mw.log#deprecate to create an access container for tracking.
663 * Store for messages.
670 * Store for templates associated with a module.
674 templates
: new Map(),
677 * Get a message object.
679 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
682 * @param {string} key Key of message to get
683 * @param {...Mixed} parameters Values for $N replacements
684 * @return {mw.Message}
686 message: function ( key
) {
687 var parameters
= slice
.call( arguments
, 1 );
688 return new Message( mw
.messages
, key
, parameters
);
692 * Get a message string using the (default) 'text' format.
694 * Shortcut for `mw.message( key, parameters... ).text()`.
697 * @param {string} key Key of message to get
698 * @param {...Mixed} parameters Values for $N replacements
702 return mw
.message
.apply( mw
.message
, arguments
).toString();
706 * No-op dummy placeholder for {@link mw.log} in debug mode.
713 * Client for ResourceLoader server end point.
715 * This client is in charge of maintaining the module registry and state
716 * machine, initiating network (batch) requests for loading modules, as
717 * well as dependency resolution and execution of source code.
719 * For more information, refer to
720 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
725 loader
: ( function () {
728 * Fired via mw.track on various resource loading errors.
730 * @event resourceloader_exception
731 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
732 * object, but in theory module code could manually throw something else, and that
733 * might also end up here.
734 * @param {string} [module] Name of the module which caused the error. Omitted if the
735 * error is not module-related or the module cannot be easily identified due to
737 * @param {string} source Source of the error. Possible values:
739 * - style: stylesheet error (only affects old IE where a special style loading method
741 * - load-callback: exception thrown by user callback
742 * - module-execute: exception thrown by module code
743 * - store-eval: could not evaluate module code cached in localStorage
744 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
745 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
746 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
750 * Fired via mw.track on resource loading error conditions.
752 * @event resourceloader_assert
753 * @param {string} source Source of the error. Possible values:
755 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
756 * bug; see <https://phabricator.wikimedia.org/T59567> for details
760 * Mapping of registered modules.
762 * See #implement and #execute for exact details on support for script, style and messages.
768 * // From mw.loader.register()
769 * 'version': '########' (hash)
770 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
771 * 'group': 'somegroup', (or) null
772 * 'source': 'local', (or) 'anotherwiki'
773 * 'skip': 'return !!window.Example', (or) null
774 * 'module': export Object
776 * // Set from execute() or mw.loader.state()
777 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
779 * // Optionally added at run-time by mw.loader.implement()
781 * 'script': closure, array of urls, or string
782 * 'style': { ... } (see #execute)
783 * 'messages': { 'key': 'value', ... }
790 * The module is known to the system but not yet required.
791 * Meta data is registered via mw.loader#register. Calls to that method are
792 * generated server-side by the startup module.
794 * The module was required through mw.loader (either directly or as dependency of
795 * another module). The client will fetch module contents from the server.
796 * The contents are then stashed in the registry via mw.loader#implement.
798 * The module has been loaded from the server and stashed via mw.loader#implement.
799 * If the module has no more dependencies in-flight, the module will be executed
800 * immediately. Otherwise execution is deferred, controlled via #handlePending.
802 * The module is being executed.
804 * The module has been successfully executed.
806 * The module (or one of its dependencies) produced an error during execution.
808 * The module was registered client-side and requested, but the server denied knowledge
809 * of the module's existence.
815 // Mapping of sources, keyed by source-id, values are strings.
820 // 'sourceId': 'http://example.org/w/load.php'
825 // For queueModuleScript()
826 handlingPendingRequests
= false,
827 pendingRequests
= [],
829 // List of modules to be loaded
833 * List of callback jobs waiting for modules to be ready.
835 * Jobs are created by #enqueue() and run by #handlePending().
837 * Typically when a job is created for a module, the job's dependencies contain
838 * both the required module and all its recursive dependencies.
843 * 'dependencies': [ module names ],
844 * 'ready': Function callback
845 * 'error': Function callback
848 * @property {Object[]} jobs
856 // For addEmbeddedCSS()
858 cssBufferTimer
= null,
859 cssCallbacks
= $.Callbacks(),
860 isIE9
= document
.documentMode
=== 9,
861 rAF
= window
.requestAnimationFrame
|| setTimeout
;
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 if ( !cssBufferTimer
) {
934 cssBufferTimer
= rAF( function () {
935 // Wrap in anonymous function that takes no arguments
936 // Support: Firefox < 13
937 // Firefox 12 has non-standard behaviour of passing a number
938 // as first argument to a setTimeout callback.
939 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
946 // This is a scheduled flush for the buffer
948 cssBufferTimer
= null;
953 // By default, always create a new <style>. Appending text to a <style> tag is
954 // is a performance anti-pattern as it requires CSS to be reparsed (T47810).
957 // Try to re-use existing <style> tags due to the IE stylesheet limit (T33676).
959 $style
= $( getMarker() ).prev();
960 // Verify that the element before the marker actually is a <style> tag created
961 // by mw.loader (not some other style tag, or e.g. a <meta> tag).
962 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) ) {
963 styleEl
= $style
[ 0 ];
964 styleEl
.appendChild( document
.createTextNode( cssText
) );
968 // Else: No existing tag to reuse. Continue below and create the first one.
971 $style
= $( newStyleTag( cssText
, getMarker() ) );
974 $style
.data( 'ResourceLoaderDynamicStyleTag', true );
982 * @param {Array} modules List of module names
983 * @return {string} Hash of concatenated version hashes.
985 function getCombinedVersion( modules
) {
986 var hashes
= $.map( modules
, function ( module
) {
987 return registry
[ module
].version
;
989 return fnv132( hashes
.join( '' ) );
993 * Determine whether all dependencies are in state 'ready', which means we may
994 * execute the module or job now.
997 * @param {Array} modules Names of modules to be checked
998 * @return {boolean} True if all modules are in state 'ready', false otherwise
1000 function allReady( modules
) {
1002 for ( i
= 0; i
< modules
.length
; i
++ ) {
1003 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
1011 * Determine whether all dependencies are in state 'ready', which means we may
1012 * execute the module or job now.
1015 * @param {Array} modules Names of modules to be checked
1016 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1018 function anyFailed( modules
) {
1020 for ( i
= 0; i
< modules
.length
; i
++ ) {
1021 state
= mw
.loader
.getState( modules
[ i
] );
1022 if ( state
=== 'error' || state
=== 'missing' ) {
1030 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1031 * pending jobs and modules that depend upon this module. If the given module failed,
1032 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1033 * all jobs/modules now having their dependencies satisfied.
1035 * Jobs that depend on a failed module, will have their error callback ran (if any).
1038 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1040 function handlePending( module
) {
1041 var j
, job
, hasErrors
, m
, stateChange
;
1043 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1044 // If the current module failed, mark all dependent modules also as failed.
1045 // Iterate until steady-state to propagate the error state upwards in the
1048 stateChange
= false;
1049 for ( m
in registry
) {
1050 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1051 if ( anyFailed( registry
[ m
].dependencies
) ) {
1052 registry
[ m
].state
= 'error';
1057 } while ( stateChange
);
1060 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1061 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1062 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1063 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1064 // All dependencies satisfied, or some have errors
1066 jobs
.splice( j
, 1 );
1070 if ( typeof job
.error
=== 'function' ) {
1071 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1074 if ( typeof job
.ready
=== 'function' ) {
1079 // A user-defined callback raised an exception.
1080 // Swallow it to protect our state machine!
1081 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1086 if ( registry
[ module
].state
=== 'ready' ) {
1087 // The current module became 'ready'. Set it in the module store, and recursively execute all
1088 // dependent modules that are loaded and now have all dependencies satisfied.
1089 mw
.loader
.store
.set( module
, registry
[ module
] );
1090 for ( m
in registry
) {
1091 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1099 * Resolve dependencies and detect circular references.
1102 * @param {string} module Name of the top-level module whose dependencies shall be
1103 * resolved and sorted.
1104 * @param {Array} resolved Returns a topological sort of the given module and its
1105 * dependencies, such that later modules depend on earlier modules. The array
1106 * contains the module names. If the array contains already some module names,
1107 * this function appends its result to the pre-existing array.
1108 * @param {StringSet} [unresolved] Used to track the current dependency
1109 * chain, and to report loops in the dependency graph.
1110 * @throws {Error} If any unregistered module or a dependency loop is encountered
1112 function sortDependencies( module
, resolved
, unresolved
) {
1115 if ( !hasOwn
.call( registry
, module
) ) {
1116 throw new Error( 'Unknown dependency: ' + module
);
1119 if ( registry
[ module
].skip
!== null ) {
1120 // eslint-disable-next-line no-new-func
1121 skip
= new Function( registry
[ module
].skip
);
1122 registry
[ module
].skip
= null;
1124 registry
[ module
].skipped
= true;
1125 registry
[ module
].dependencies
= [];
1126 registry
[ module
].state
= 'ready';
1127 handlePending( module
);
1132 // Resolves dynamic loader function and replaces it with its own results
1133 if ( typeof registry
[ module
].dependencies
=== 'function' ) {
1134 registry
[ module
].dependencies
= registry
[ module
].dependencies();
1135 // Ensures the module's dependencies are always in an array
1136 if ( typeof registry
[ module
].dependencies
!== 'object' ) {
1137 registry
[ module
].dependencies
= [ registry
[ module
].dependencies
];
1140 if ( $.inArray( module
, resolved
) !== -1 ) {
1141 // Module already resolved; nothing to do
1144 // Create unresolved if not passed in
1145 if ( !unresolved
) {
1146 unresolved
= new StringSet();
1148 // Tracks down dependencies
1149 deps
= registry
[ module
].dependencies
;
1150 for ( i
= 0; i
< deps
.length
; i
++ ) {
1151 if ( $.inArray( deps
[ i
], resolved
) === -1 ) {
1152 if ( unresolved
.has( deps
[ i
] ) ) {
1153 throw new Error( mw
.format(
1154 'Circular reference detected: $1 -> $2',
1160 unresolved
.add( module
);
1161 sortDependencies( deps
[ i
], resolved
, unresolved
);
1164 resolved
.push( module
);
1168 * Get names of module that a module depends on, in their proper dependency order.
1171 * @param {string[]} modules Array of string module names
1172 * @return {Array} List of dependencies, including 'module'.
1173 * @throws {Error} If an unregistered module or a dependency loop is encountered
1175 function resolve( modules
) {
1176 var i
, resolved
= [];
1177 for ( i
= 0; i
< modules
.length
; i
++ ) {
1178 sortDependencies( modules
[ i
], resolved
);
1184 * Load and execute a script.
1187 * @param {string} src URL to script, will be used as the src attribute in the script tag
1188 * @return {jQuery.Promise}
1190 function addScript( src
) {
1194 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1195 // XHR for a same domain request instead of <script>, which changes the request
1196 // headers (potentially missing a cache hit), and reduces caching in general
1197 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1198 // text, so we'd need to $.globalEval, which then messes up line numbers.
1205 * Queue the loading and execution of a script for a particular module.
1208 * @param {string} src URL of the script
1209 * @param {string} [moduleName] Name of currently executing module
1210 * @return {jQuery.Promise}
1212 function queueModuleScript( src
, moduleName
) {
1213 var r
= $.Deferred();
1215 pendingRequests
.push( function () {
1216 if ( moduleName
&& hasOwn
.call( registry
, moduleName
) ) {
1217 // Emulate runScript() part of execute()
1218 window
.require
= mw
.loader
.require
;
1219 window
.module
= registry
[ moduleName
].module
;
1221 addScript( src
).always( function () {
1222 // 'module.exports' should not persist after the file is executed to
1223 // avoid leakage to unrelated code. 'require' should be kept, however,
1224 // as asynchronous access to 'require' is allowed and expected. (T144879)
1225 delete window
.module
;
1228 // Start the next one (if any)
1229 if ( pendingRequests
[ 0 ] ) {
1230 pendingRequests
.shift()();
1232 handlingPendingRequests
= false;
1236 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1237 handlingPendingRequests
= true;
1238 pendingRequests
.shift()();
1244 * Utility function for execute()
1247 * @param {string} [media] Media attribute
1248 * @param {string} url URL
1250 function addLink( media
, url
) {
1251 var el
= document
.createElement( 'link' );
1253 el
.rel
= 'stylesheet';
1254 if ( media
&& media
!== 'all' ) {
1257 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1258 // see #addEmbeddedCSS, T33676, and T49277 for details.
1261 $( getMarker() ).before( el
);
1265 * Executes a loaded module, making it ready to use
1268 * @param {string} module Module name to execute
1270 function execute( module
) {
1271 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1272 cssHandlesRegistered
= false;
1274 if ( !hasOwn
.call( registry
, module
) ) {
1275 throw new Error( 'Module has not been registered yet: ' + module
);
1277 if ( registry
[ module
].state
!== 'loaded' ) {
1278 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1281 registry
[ module
].state
= 'executing';
1283 runScript = function () {
1284 var script
, markModuleReady
, nestedAddScript
, legacyWait
, implicitDependencies
,
1285 // Expand to include dependencies since we have to exclude both legacy modules
1286 // and their dependencies from the legacyWait (to prevent a circular dependency).
1287 legacyModules
= resolve( mw
.config
.get( 'wgResourceLoaderLegacyModules', [] ) );
1289 script
= registry
[ module
].script
;
1290 markModuleReady = function () {
1291 registry
[ module
].state
= 'ready';
1292 handlePending( module
);
1294 nestedAddScript = function ( arr
, callback
, i
) {
1295 // Recursively call queueModuleScript() in its own callback
1296 // for each element of arr.
1297 if ( i
>= arr
.length
) {
1298 // We're at the end of the array
1303 queueModuleScript( arr
[ i
], module
).always( function () {
1304 nestedAddScript( arr
, callback
, i
+ 1 );
1308 implicitDependencies
= ( $.inArray( module
, legacyModules
) !== -1 ) ?
1312 if ( module
=== 'user' ) {
1313 // Implicit dependency on the site module. Not real dependency because
1314 // it should run after 'site' regardless of whether it succeeds or fails.
1315 implicitDependencies
.push( 'site' );
1318 legacyWait
= implicitDependencies
.length
?
1319 mw
.loader
.using( implicitDependencies
) :
1320 $.Deferred().resolve();
1322 legacyWait
.always( function () {
1324 if ( $.isArray( script
) ) {
1325 nestedAddScript( script
, markModuleReady
, 0 );
1326 } else if ( typeof script
=== 'function' ) {
1327 // Pass jQuery twice so that the signature of the closure which wraps
1328 // the script can bind both '$' and 'jQuery'.
1329 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1332 } else if ( typeof script
=== 'string' ) {
1333 // Site and user modules are legacy scripts that run in the global scope.
1334 // This is transported as a string instead of a function to avoid needing
1335 // to use string manipulation to undo the function wrapper.
1336 $.globalEval( script
);
1340 // Module without script
1344 // Use mw.track instead of mw.log because these errors are common in production mode
1345 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1346 registry
[ module
].state
= 'error';
1347 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1348 handlePending( module
);
1353 // Add localizations to message system
1354 if ( registry
[ module
].messages
) {
1355 mw
.messages
.set( registry
[ module
].messages
);
1358 // Initialise templates
1359 if ( registry
[ module
].templates
) {
1360 mw
.templates
.set( module
, registry
[ module
].templates
);
1363 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1366 checkCssHandles = function () {
1367 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1368 // one of the cssHandles is fired while we're still creating more handles.
1369 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1371 runScript
= undefined; // Revoke
1374 cssHandle = function () {
1375 var check
= checkCssHandles
;
1377 return function () {
1381 check
= undefined; // Revoke
1387 // Process styles (see also mw.loader.implement)
1388 // * back-compat: { <media>: css }
1389 // * back-compat: { <media>: [url, ..] }
1390 // * { "css": [css, ..] }
1391 // * { "url": { <media>: [url, ..] } }
1392 if ( registry
[ module
].style
) {
1393 for ( key
in registry
[ module
].style
) {
1394 value
= registry
[ module
].style
[ key
];
1397 if ( key
!== 'url' && key
!== 'css' ) {
1398 // Backwards compatibility, key is a media-type
1399 if ( typeof value
=== 'string' ) {
1400 // back-compat: { <media>: css }
1401 // Ignore 'media' because it isn't supported (nor was it used).
1402 // Strings are pre-wrapped in "@media". The media-type was just ""
1403 // (because it had to be set to something).
1404 // This is one of the reasons why this format is no longer used.
1405 addEmbeddedCSS( value
, cssHandle() );
1407 // back-compat: { <media>: [url, ..] }
1413 // Array of css strings in key 'css',
1414 // or back-compat array of urls from media-type
1415 if ( $.isArray( value
) ) {
1416 for ( i
= 0; i
< value
.length
; i
++ ) {
1417 if ( key
=== 'bc-url' ) {
1418 // back-compat: { <media>: [url, ..] }
1419 addLink( media
, value
[ i
] );
1420 } else if ( key
=== 'css' ) {
1421 // { "css": [css, ..] }
1422 addEmbeddedCSS( value
[ i
], cssHandle() );
1425 // Not an array, but a regular object
1426 // Array of urls inside media-type key
1427 } else if ( typeof value
=== 'object' ) {
1428 // { "url": { <media>: [url, ..] } }
1429 for ( media
in value
) {
1430 urls
= value
[ media
];
1431 for ( i
= 0; i
< urls
.length
; i
++ ) {
1432 addLink( media
, urls
[ i
] );
1440 cssHandlesRegistered
= true;
1445 * Add one or more modules to the module load queue.
1450 * @param {string|string[]} dependencies Module name or array of string module names
1451 * @param {Function} [ready] Callback to execute when all dependencies are ready
1452 * @param {Function} [error] Callback to execute when any dependency fails
1454 function enqueue( dependencies
, ready
, error
) {
1455 // Allow calling by single module name
1456 if ( typeof dependencies
=== 'string' ) {
1457 dependencies
= [ dependencies
];
1460 // Add ready and error callbacks if they were given
1461 if ( ready
!== undefined || error
!== undefined ) {
1463 // Narrow down the list to modules that are worth waiting for
1464 dependencies
: $.grep( dependencies
, function ( module
) {
1465 var state
= mw
.loader
.getState( module
);
1466 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1473 $.each( dependencies
, function ( idx
, module
) {
1474 var state
= mw
.loader
.getState( module
);
1475 // Only queue modules that are still in the initial 'registered' state
1476 // (not ones already loading, ready or error).
1477 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1478 // Private modules must be embedded in the page. Don't bother queuing
1479 // these as the server will deny them anyway (T101806).
1480 if ( registry
[ module
].group
=== 'private' ) {
1481 registry
[ module
].state
= 'error';
1482 handlePending( module
);
1485 queue
.push( module
);
1492 function sortQuery( o
) {
1498 if ( hasOwn
.call( o
, key
) ) {
1503 for ( key
= 0; key
< a
.length
; key
++ ) {
1504 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1510 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1511 * to a query string of the form foo.bar,baz|bar.baz,quux
1514 * @param {Object} moduleMap Module map
1515 * @return {string} Module query string
1517 function buildModulesString( moduleMap
) {
1521 for ( prefix
in moduleMap
) {
1522 p
= prefix
=== '' ? '' : prefix
+ '.';
1523 arr
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1525 return arr
.join( '|' );
1529 * Make a network request to load modules from the server.
1532 * @param {Object} moduleMap Module map, see #buildModulesString
1533 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1534 * @param {string} sourceLoadScript URL of load.php
1536 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
1537 var query
= $.extend(
1538 { modules
: buildModulesString( moduleMap
) },
1541 query
= sortQuery( query
);
1542 addScript( sourceLoadScript
+ '?' + $.param( query
) );
1546 * Resolve indexed dependencies.
1548 * ResourceLoader uses an optimization to save space which replaces module names in
1549 * dependency lists with the index of that module within the array of module
1550 * registration data if it exists. The benefit is a significant reduction in the data
1551 * size of the startup module. This function changes those dependency lists back to
1552 * arrays of strings.
1555 * @param {Array} modules Modules array
1557 function resolveIndexedDependencies( modules
) {
1559 function resolveIndex( dep
) {
1560 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1562 for ( i
= 0; i
< modules
.length
; i
++ ) {
1563 deps
= modules
[ i
][ 2 ];
1565 for ( j
= 0; j
< deps
.length
; j
++ ) {
1566 deps
[ j
] = resolveIndex( deps
[ j
] );
1573 * Create network requests for a batch of modules.
1575 * This is an internal method for #work(). This must not be called directly
1576 * unless the modules are already registered, and no request is in progress,
1577 * and the module state has already been set to `loading`.
1580 * @param {string[]} batch
1582 function batchRequest( batch
) {
1583 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1584 source
, group
, i
, modules
, sourceLoadScript
,
1585 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1586 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1588 if ( !batch
.length
) {
1592 // Always order modules alphabetically to help reduce cache
1593 // misses for otherwise identical content.
1596 // Build a list of query parameters common to all requests
1598 skin
: mw
.config
.get( 'skin' ),
1599 lang
: mw
.config
.get( 'wgUserLanguage' ),
1600 debug
: mw
.config
.get( 'debug' )
1602 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1604 // Split module list by source and by group.
1606 for ( b
= 0; b
< batch
.length
; b
++ ) {
1607 bSource
= registry
[ batch
[ b
] ].source
;
1608 bGroup
= registry
[ batch
[ b
] ].group
;
1609 if ( !hasOwn
.call( splits
, bSource
) ) {
1610 splits
[ bSource
] = {};
1612 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1613 splits
[ bSource
][ bGroup
] = [];
1615 bSourceGroup
= splits
[ bSource
][ bGroup
];
1616 bSourceGroup
.push( batch
[ b
] );
1619 for ( source
in splits
) {
1621 sourceLoadScript
= sources
[ source
];
1623 for ( group
in splits
[ source
] ) {
1625 // Cache access to currently selected list of
1626 // modules for this group from this source.
1627 modules
= splits
[ source
][ group
];
1629 currReqBase
= $.extend( {
1630 version
: getCombinedVersion( modules
)
1632 // For user modules append a user name to the query string.
1633 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1634 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1636 currReqBaseLength
= $.param( currReqBase
).length
;
1637 // We may need to split up the request to honor the query string length limit,
1638 // so build it piece by piece.
1639 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1641 moduleMap
= {}; // { prefix: [ suffixes ] }
1643 for ( i
= 0; i
< modules
.length
; i
++ ) {
1644 // Determine how many bytes this module would add to the query string
1645 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1647 // If lastDotIndex is -1, substr() returns an empty string
1648 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1649 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1651 bytesAdded
= hasOwn
.call( moduleMap
, prefix
) ?
1652 suffix
.length
+ 3 : // '%2C'.length == 3
1653 modules
[ i
].length
+ 3; // '%7C'.length == 3
1655 // If the url would become too long, create a new one,
1656 // but don't create empty requests
1657 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1658 // This url would become too long, create a new one, and start the old one
1659 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1661 l
= currReqBaseLength
+ 9;
1662 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1664 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1665 moduleMap
[ prefix
] = [];
1667 moduleMap
[ prefix
].push( suffix
);
1670 // If there's anything left in moduleMap, request that too
1671 if ( !$.isEmptyObject( moduleMap
) ) {
1672 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1680 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1681 * form of calls to mw.loader#implement().
1682 * @param {Function} cb Callback in case of failure
1683 * @param {Error} cb.err
1685 function asyncEval( implementations
, cb
) {
1686 if ( !implementations
.length
) {
1689 mw
.requestIdleCallback( function () {
1691 $.globalEval( implementations
.join( ';' ) );
1699 * Make a versioned key for a specific module.
1702 * @param {string} module Module name
1703 * @return {string|null} Module key in format '`[name]@[version]`',
1704 * or null if the module does not exist
1706 function getModuleKey( module
) {
1707 return hasOwn
.call( registry
, module
) ?
1708 ( module
+ '@' + registry
[ module
].version
) : null;
1713 * @param {string} key Module name or '`[name]@[version]`'
1716 function splitModuleKey( key
) {
1717 var index
= key
.indexOf( '@' );
1718 if ( index
=== -1 ) {
1719 return { name
: key
};
1722 name
: key
.slice( 0, index
),
1723 version
: key
.slice( index
+ 1 )
1727 /* Public Members */
1730 * The module registry is exposed as an aid for debugging and inspecting page
1731 * state; it is not a public interface for modifying the registry.
1737 moduleRegistry
: registry
,
1740 * @inheritdoc #newStyleTag
1743 addStyleTag
: newStyleTag
,
1746 * Start loading of all queued module dependencies.
1751 var q
, batch
, implementations
, sourceModules
;
1755 // Appends a list of modules from the queue to the batch
1756 for ( q
= 0; q
< queue
.length
; q
++ ) {
1757 // Only load modules which are registered
1758 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1759 // Prevent duplicate entries
1760 if ( $.inArray( queue
[ q
], batch
) === -1 ) {
1761 batch
.push( queue
[ q
] );
1762 // Mark registered modules as loading
1763 registry
[ queue
[ q
] ].state
= 'loading';
1768 // Now that the queue has been processed into a batch, clear the queue.
1769 // This MUST happen before we initiate any eval or network request. Otherwise,
1770 // it is possible for a cached script to instantly trigger the same work queue
1771 // again; all before we've cleared it causing each request to include modules
1772 // which are already loaded.
1775 if ( !batch
.length
) {
1779 mw
.loader
.store
.init();
1780 if ( mw
.loader
.store
.enabled
) {
1781 implementations
= [];
1783 batch
= $.grep( batch
, function ( module
) {
1784 var implementation
= mw
.loader
.store
.get( module
);
1785 if ( implementation
) {
1786 implementations
.push( implementation
);
1787 sourceModules
.push( module
);
1792 asyncEval( implementations
, function ( err
) {
1794 // Not good, the cached mw.loader.implement calls failed! This should
1795 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1796 // Depending on how corrupt the string is, it is likely that some
1797 // modules' implement() succeeded while the ones after the error will
1798 // never run and leave their modules in the 'loading' state forever.
1799 mw
.loader
.store
.stats
.failed
++;
1801 // Since this is an error not caused by an individual module but by
1802 // something that infected the implement call itself, don't take any
1803 // risks and clear everything in this cache.
1804 mw
.loader
.store
.clear();
1806 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1807 // Re-add the failed ones that are still pending back to the batch
1808 failed
= $.grep( sourceModules
, function ( module
) {
1809 return registry
[ module
].state
=== 'loading';
1811 batchRequest( failed
);
1815 batchRequest( batch
);
1819 * Register a source.
1821 * The #work() method will use this information to split up requests by source.
1823 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1825 * @param {string|Object} id Source ID, or object mapping ids to load urls
1826 * @param {string} loadUrl Url to a load.php end point
1827 * @throws {Error} If source id is already registered
1829 addSource: function ( id
, loadUrl
) {
1831 // Allow multiple additions
1832 if ( typeof id
=== 'object' ) {
1833 for ( source
in id
) {
1834 mw
.loader
.addSource( source
, id
[ source
] );
1839 if ( hasOwn
.call( sources
, id
) ) {
1840 throw new Error( 'source already registered: ' + id
);
1843 sources
[ id
] = loadUrl
;
1847 * Register a module, letting the system know about it and its properties.
1849 * The startup modules contain calls to this method.
1851 * When using multiple module registration by passing an array, dependencies that
1852 * are specified as references to modules within the array will be resolved before
1853 * the modules are registered.
1855 * @param {string|Array} module Module name or array of arrays, each containing
1856 * a list of arguments compatible with this method
1857 * @param {string|number} version Module version hash (falls backs to empty string)
1858 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1859 * @param {string|Array|Function} dependencies One string or array of strings of module
1860 * names on which this module depends, or a function that returns that array.
1861 * @param {string} [group=null] Group which the module is in
1862 * @param {string} [source='local'] Name of the source
1863 * @param {string} [skip=null] Script body of the skip function
1865 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1867 // Allow multiple registration
1868 if ( typeof module
=== 'object' ) {
1869 resolveIndexedDependencies( module
);
1870 for ( i
= 0; i
< module
.length
; i
++ ) {
1871 // module is an array of module names
1872 if ( typeof module
[ i
] === 'string' ) {
1873 mw
.loader
.register( module
[ i
] );
1874 // module is an array of arrays
1875 } else if ( typeof module
[ i
] === 'object' ) {
1876 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1881 if ( hasOwn
.call( registry
, module
) ) {
1882 throw new Error( 'module already registered: ' + module
);
1884 if ( typeof dependencies
=== 'string' ) {
1885 // A single module name
1886 deps
= [ dependencies
];
1887 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
1888 // Array of module names or a function that returns an array
1889 deps
= dependencies
;
1891 // List the module as registered
1892 registry
[ module
] = {
1893 // Exposed to execute() for mw.loader.implement() closures.
1894 // Import happens via require().
1898 version
: version
!== undefined ? String( version
) : '',
1899 dependencies
: deps
|| [],
1900 group
: typeof group
=== 'string' ? group
: null,
1901 source
: typeof source
=== 'string' ? source
: 'local',
1902 state
: 'registered',
1903 skip
: typeof skip
=== 'string' ? skip
: null
1908 * Implement a module given the components that make up the module.
1910 * When #load() or #using() requests one or more modules, the server
1911 * response contain calls to this function.
1913 * @param {string} module Name of module and current module version. Formatted
1914 * as '`[name]@[version]`". This version should match the requested version
1915 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1916 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1917 * @param {Function|Array|string} [script] Function with module code, list of URLs
1918 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1919 * @param {Object} [style] Should follow one of the following patterns:
1921 * { "css": [css, ..] }
1922 * { "url": { <media>: [url, ..] } }
1924 * And for backwards compatibility (needs to be supported forever due to caching):
1927 * { <media>: [url, ..] }
1929 * The reason css strings are not concatenated anymore is T33676. We now check
1930 * whether it's safe to extend the stylesheet.
1933 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1934 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1936 implement: function ( module
, script
, style
, messages
, templates
) {
1937 var split
= splitModuleKey( module
),
1939 version
= split
.version
;
1940 // Automatically register module
1941 if ( !hasOwn
.call( registry
, name
) ) {
1942 mw
.loader
.register( name
);
1944 // Check for duplicate implementation
1945 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1946 throw new Error( 'module already implemented: ' + name
);
1949 // Without this reset, if there is a version mismatch between the
1950 // requested and received module version, then mw.loader.store would
1951 // cache the response under the requested key. Thus poisoning the cache
1952 // indefinitely with a stale value. (T117587)
1953 registry
[ name
].version
= version
;
1955 // Attach components
1956 registry
[ name
].script
= script
|| null;
1957 registry
[ name
].style
= style
|| null;
1958 registry
[ name
].messages
= messages
|| null;
1959 registry
[ name
].templates
= templates
|| null;
1960 // The module may already have been marked as erroneous
1961 if ( $.inArray( registry
[ name
].state
, [ 'error', 'missing' ] ) === -1 ) {
1962 registry
[ name
].state
= 'loaded';
1963 if ( allReady( registry
[ name
].dependencies
) ) {
1970 * Execute a function as soon as one or more required modules are ready.
1972 * Example of inline dependency on OOjs:
1974 * mw.loader.using( 'oojs', function () {
1975 * OO.compare( [ 1 ], [ 1 ] );
1978 * Since MediaWiki 1.23 this also returns a promise.
1980 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1982 * @param {string|Array} dependencies Module name or array of modules names the
1983 * callback depends on to be ready before executing
1984 * @param {Function} [ready] Callback to execute when all dependencies are ready
1985 * @param {Function} [error] Callback to execute if one or more dependencies failed
1986 * @return {jQuery.Promise} With a `require` function
1988 using: function ( dependencies
, ready
, error
) {
1989 var deferred
= $.Deferred();
1991 // Allow calling with a single dependency as a string
1992 if ( typeof dependencies
=== 'string' ) {
1993 dependencies
= [ dependencies
];
1997 deferred
.done( ready
);
2000 deferred
.fail( error
);
2004 // Resolve entire dependency map
2005 dependencies
= resolve( dependencies
);
2007 return deferred
.reject( e
).promise();
2009 if ( allReady( dependencies
) ) {
2010 // Run ready immediately
2011 deferred
.resolve( mw
.loader
.require
);
2012 } else if ( anyFailed( dependencies
) ) {
2013 // Execute error immediately if any dependencies have errors
2015 new Error( 'One or more dependencies failed to load' ),
2019 // Not all dependencies are ready, add to the load queue
2020 enqueue( dependencies
, function () {
2021 deferred
.resolve( mw
.loader
.require
);
2022 }, deferred
.reject
);
2025 return deferred
.promise();
2029 * Load an external script or one or more modules.
2031 * @param {string|Array} modules Either the name of a module, array of modules,
2032 * or a URL of an external script or style
2033 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2034 * external script or style; acceptable values are "text/css" and
2035 * "text/javascript"; if no type is provided, text/javascript is assumed.
2037 load: function ( modules
, type
) {
2040 // Allow calling with a url or single dependency as a string
2041 if ( typeof modules
=== 'string' ) {
2042 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2043 if ( /^(https?:)?\/?\//.test( modules
) ) {
2044 if ( type
=== 'text/css' ) {
2046 // Use properties instead of attributes as IE throws security
2047 // warnings when inserting a <link> tag with a protocol-relative
2048 // URL set though attributes - when on HTTPS. See T43331.
2049 l
= document
.createElement( 'link' );
2050 l
.rel
= 'stylesheet';
2052 $( 'head' ).append( l
);
2055 if ( type
=== 'text/javascript' || type
=== undefined ) {
2056 addScript( modules
);
2060 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2062 // Called with single module
2063 modules
= [ modules
];
2066 // Filter out undefined modules, otherwise resolve() will throw
2067 // an exception for trying to load an undefined module.
2068 // Undefined modules are acceptable here in load(), because load() takes
2069 // an array of unrelated modules, whereas the modules passed to
2070 // using() are related and must all be loaded.
2071 filtered
= $.grep( modules
, function ( module
) {
2072 var state
= mw
.loader
.getState( module
);
2073 return state
!== null && state
!== 'error' && state
!== 'missing';
2076 if ( filtered
.length
=== 0 ) {
2079 // Resolve entire dependency map
2080 filtered
= resolve( filtered
);
2081 // If all modules are ready, or if any modules have errors, nothing to be done.
2082 if ( allReady( filtered
) || anyFailed( filtered
) ) {
2085 // Some modules are not yet ready, add to module load queue.
2086 enqueue( filtered
, undefined, undefined );
2090 * Change the state of one or more modules.
2092 * @param {string|Object} module Module name or object of module name/state pairs
2093 * @param {string} state State name
2095 state: function ( module
, state
) {
2098 if ( typeof module
=== 'object' ) {
2099 for ( m
in module
) {
2100 mw
.loader
.state( m
, module
[ m
] );
2104 if ( !hasOwn
.call( registry
, module
) ) {
2105 mw
.loader
.register( module
);
2107 registry
[ module
].state
= state
;
2108 if ( $.inArray( state
, [ 'ready', 'error', 'missing' ] ) !== -1 ) {
2109 // Make sure pending modules depending on this one get executed if their
2110 // dependencies are now fulfilled!
2111 handlePending( module
);
2116 * Get the version of a module.
2118 * @param {string} module Name of module
2119 * @return {string|null} The version, or null if the module (or its version) is not
2122 getVersion: function ( module
) {
2123 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].version
=== undefined ) {
2126 return registry
[ module
].version
;
2130 * Get the state of a module.
2132 * @param {string} module Name of module
2133 * @return {string|null} The state, or null if the module (or its state) is not
2136 getState: function ( module
) {
2137 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].state
=== undefined ) {
2140 return registry
[ module
].state
;
2144 * Get the names of all registered modules.
2148 getModuleNames: function () {
2149 return $.map( registry
, function ( i
, key
) {
2155 * Get the exported value of a module.
2157 * Modules may provide this via their local `module.exports`.
2161 * @param {string} moduleName Module name
2162 * @return {Mixed} Exported value
2164 require: function ( moduleName
) {
2165 var state
= mw
.loader
.getState( moduleName
);
2167 // Only ready modules can be required
2168 if ( state
!== 'ready' ) {
2169 // Module may've forgotten to declare a dependency
2170 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2173 return registry
[ moduleName
].module
.exports
;
2177 * @inheritdoc mw.inspect#runReports
2180 inspect: function () {
2181 var args
= slice
.call( arguments
);
2182 mw
.loader
.using( 'mediawiki.inspect', function () {
2183 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2188 * On browsers that implement the localStorage API, the module store serves as a
2189 * smart complement to the browser cache. Unlike the browser cache, the module store
2190 * can slice a concatenated response from ResourceLoader into its constituent
2191 * modules and cache each of them separately, using each module's versioning scheme
2192 * to determine when the cache should be invalidated.
2195 * @class mw.loader.store
2198 // Whether the store is in use on this page.
2201 // Modules whose string representation exceeds 100 kB are
2202 // ineligible for storage. See bug T66721.
2203 MODULE_SIZE_MAX
: 100 * 1000,
2205 // The contents of the store, mapping '[name]@[version]' keys
2206 // to module implementations.
2210 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2213 * Construct a JSON-serializable object representing the content of the store.
2215 * @return {Object} Module store contents.
2217 toJSON: function () {
2218 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2222 * Get the localStorage key for the entire module store. The key references
2223 * $wgDBname to prevent clashes between wikis which share a common host.
2225 * @return {string} localStorage item key
2227 getStoreKey: function () {
2228 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2232 * Get a key on which to vary the module cache.
2234 * @return {string} String of concatenated vary conditions.
2236 getVary: function () {
2238 mw
.config
.get( 'skin' ),
2239 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2240 mw
.config
.get( 'wgUserLanguage' )
2245 * Initialize the store.
2247 * Retrieves store from localStorage and (if successfully retrieved) decoding
2248 * the stored JSON value to a plain object.
2250 * The try / catch block is used for JSON & localStorage feature detection.
2251 * See the in-line documentation for Modernizr's localStorage feature detection
2252 * code for a full account of why we need a try / catch:
2253 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2258 if ( mw
.loader
.store
.enabled
!== null ) {
2264 // Disabled because localStorage quotas are tight and (in Firefox's case)
2265 // shared by multiple origins.
2266 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2267 /Firefox|Opera/.test( navigator
.userAgent
) ||
2269 // Disabled by configuration.
2270 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2272 // Clear any previous store to free up space. (T66721)
2273 mw
.loader
.store
.clear();
2274 mw
.loader
.store
.enabled
= false;
2277 if ( mw
.config
.get( 'debug' ) ) {
2278 // Disable module store in debug mode
2279 mw
.loader
.store
.enabled
= false;
2284 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2285 // If we get here, localStorage is available; mark enabled
2286 mw
.loader
.store
.enabled
= true;
2287 data
= JSON
.parse( raw
);
2288 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2289 mw
.loader
.store
.items
= data
.items
;
2293 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2296 if ( raw
=== undefined ) {
2297 // localStorage failed; disable store
2298 mw
.loader
.store
.enabled
= false;
2300 mw
.loader
.store
.update();
2305 * Retrieve a module from the store and update cache hit stats.
2307 * @param {string} module Module name
2308 * @return {string|boolean} Module implementation or false if unavailable
2310 get: function ( module
) {
2313 if ( !mw
.loader
.store
.enabled
) {
2317 key
= getModuleKey( module
);
2318 if ( key
in mw
.loader
.store
.items
) {
2319 mw
.loader
.store
.stats
.hits
++;
2320 return mw
.loader
.store
.items
[ key
];
2322 mw
.loader
.store
.stats
.misses
++;
2327 * Stringify a module and queue it for storage.
2329 * @param {string} module Module name
2330 * @param {Object} descriptor The module's descriptor as set in the registry
2331 * @return {boolean} Module was set
2333 set: function ( module
, descriptor
) {
2336 if ( !mw
.loader
.store
.enabled
) {
2340 key
= getModuleKey( module
);
2343 // Already stored a copy of this exact version
2344 key
in mw
.loader
.store
.items
||
2345 // Module failed to load
2346 descriptor
.state
!== 'ready' ||
2347 // Unversioned, private, or site-/user-specific
2348 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user' ] ) !== -1 ) ||
2349 // Partial descriptor
2350 // (e.g. skipped module, or style module with state=ready)
2351 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2352 descriptor
.messages
, descriptor
.templates
] ) !== -1
2360 JSON
.stringify( key
),
2361 typeof descriptor
.script
=== 'function' ?
2362 String( descriptor
.script
) :
2363 JSON
.stringify( descriptor
.script
),
2364 JSON
.stringify( descriptor
.style
),
2365 JSON
.stringify( descriptor
.messages
),
2366 JSON
.stringify( descriptor
.templates
)
2368 // Attempted workaround for a possible Opera bug (bug T59567).
2369 // This regex should never match under sane conditions.
2370 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2371 args
[ 1 ] = 'function' + args
[ 1 ];
2372 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2375 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2379 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2380 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2383 mw
.loader
.store
.items
[ key
] = src
;
2384 mw
.loader
.store
.update();
2389 * Iterate through the module store, removing any item that does not correspond
2390 * (in name and version) to an item in the module registry.
2392 * @return {boolean} Store was pruned
2394 prune: function () {
2397 if ( !mw
.loader
.store
.enabled
) {
2401 for ( key
in mw
.loader
.store
.items
) {
2402 module
= key
.slice( 0, key
.indexOf( '@' ) );
2403 if ( getModuleKey( module
) !== key
) {
2404 mw
.loader
.store
.stats
.expired
++;
2405 delete mw
.loader
.store
.items
[ key
];
2406 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2407 // This value predates the enforcement of a size limit on cached modules.
2408 delete mw
.loader
.store
.items
[ key
];
2415 * Clear the entire module store right now.
2417 clear: function () {
2418 mw
.loader
.store
.items
= {};
2420 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2421 } catch ( ignored
) {}
2425 * Sync in-memory store back to localStorage.
2427 * This function debounces updates. When called with a flush already pending,
2428 * the call is coalesced into the pending update. The call to
2429 * localStorage.setItem will be naturally deferred until the page is quiescent.
2431 * Because localStorage is shared by all pages from the same origin, if multiple
2432 * pages are loaded with different module sets, the possibility exists that
2433 * modules saved by one page will be clobbered by another. But the impact would
2434 * be minor and the problem would be corrected by subsequent page views.
2438 update
: ( function () {
2439 var hasPendingWrite
= false;
2441 function flushWrites() {
2443 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2447 mw
.loader
.store
.prune();
2448 key
= mw
.loader
.store
.getStoreKey();
2450 // Replacing the content of the module store might fail if the new
2451 // contents would exceed the browser's localStorage size limit. To
2452 // avoid clogging the browser with stale data, always remove the old
2453 // value before attempting to set the new one.
2454 localStorage
.removeItem( key
);
2455 data
= JSON
.stringify( mw
.loader
.store
);
2456 localStorage
.setItem( key
, data
);
2458 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2461 hasPendingWrite
= false;
2464 return function () {
2465 if ( !hasPendingWrite
) {
2466 hasPendingWrite
= true;
2467 mw
.requestIdleCallback( flushWrites
);
2476 * HTML construction helper functions
2483 * output = Html.element( 'div', {}, new Html.Raw(
2484 * Html.element( 'img', { src: '<' } )
2486 * mw.log( output ); // <div><img src="<"/></div>
2491 html
: ( function () {
2492 function escapeCallback( s
) {
2509 * Escape a string for HTML.
2511 * Converts special characters to HTML entities.
2513 * mw.html.escape( '< > \' & "' );
2514 * // Returns < > ' & "
2516 * @param {string} s The string to escape
2517 * @return {string} HTML
2519 escape: function ( s
) {
2520 return s
.replace( /['"<>&]/g, escapeCallback
);
2524 * Create an HTML element string, with safe escaping.
2526 * @param {string} name The tag name.
2527 * @param {Object} [attrs] An object with members mapping element names to values
2528 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2530 * - string: Text to be escaped.
2531 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2532 * - this.Raw: The raw value is directly included.
2533 * - this.Cdata: The raw value is directly included. An exception is
2534 * thrown if it contains any illegal ETAGO delimiter.
2535 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2536 * @return {string} HTML
2538 element: function ( name
, attrs
, contents
) {
2539 var v
, attrName
, s
= '<' + name
;
2542 for ( attrName
in attrs
) {
2543 v
= attrs
[ attrName
];
2544 // Convert name=true, to name=name
2548 } else if ( v
=== false ) {
2551 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2554 if ( contents
=== undefined || contents
=== null ) {
2561 switch ( typeof contents
) {
2564 s
+= this.escape( contents
);
2568 // Convert to string
2569 s
+= String( contents
);
2572 if ( contents
instanceof this.Raw
) {
2573 // Raw HTML inclusion
2574 s
+= contents
.value
;
2575 } else if ( contents
instanceof this.Cdata
) {
2577 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2578 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2580 s
+= contents
.value
;
2582 throw new Error( 'mw.html.element: Invalid type of contents' );
2585 s
+= '</' + name
+ '>';
2590 * Wrapper object for raw HTML passed to mw.html.element().
2592 * @class mw.html.Raw
2594 * @param {string} value
2596 Raw: function ( value
) {
2601 * Wrapper object for CDATA element contents passed to mw.html.element()
2603 * @class mw.html.Cdata
2605 * @param {string} value
2607 Cdata: function ( value
) {
2613 // Skeleton user object, extended by the 'mediawiki.user' module.
2620 * @property {mw.Map}
2624 * @property {mw.Map}
2629 // OOUI widgets specific to MediaWiki
2633 * Registry and firing of events.
2635 * MediaWiki has various interface components that are extended, enhanced
2636 * or manipulated in some other way by extensions, gadgets and even
2639 * This framework helps streamlining the timing of when these other
2640 * code paths fire their plugins (instead of using document-ready,
2641 * which can and should be limited to firing only once).
2643 * Features like navigating to other wiki pages, previewing an edit
2644 * and editing itself – without a refresh – can then retrigger these
2645 * hooks accordingly to ensure everything still works as expected.
2649 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2650 * mw.hook( 'wikipage.content' ).fire( $content );
2652 * Handlers can be added and fired for arbitrary event names at any time. The same
2653 * event can be fired multiple times. The last run of an event is memorized
2654 * (similar to `$(document).ready` and `$.Deferred().done`).
2655 * This means if an event is fired, and a handler added afterwards, the added
2656 * function will be fired right away with the last given event data.
2658 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2659 * Thus allowing flexible use and optimal maintainability and authority control.
2660 * You can pass around the `add` and/or `fire` method to another piece of code
2661 * without it having to know the event name (or `mw.hook` for that matter).
2663 * var h = mw.hook( 'bar.ready' );
2664 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2666 * Note: Events are documented with an underscore instead of a dot in the event
2667 * name due to jsduck not supporting dots in that position.
2671 hook
: ( function () {
2675 * Create an instance of mw.hook.
2679 * @param {string} name Name of hook.
2682 return function ( name
) {
2683 var list
= hasOwn
.call( lists
, name
) ?
2685 lists
[ name
] = $.Callbacks( 'memory' );
2689 * Register a hook handler
2691 * @param {...Function} handler Function to bind.
2697 * Unregister a hook handler
2699 * @param {...Function} handler Function to unbind.
2702 remove
: list
.remove
,
2704 // eslint-disable-next-line valid-jsdoc
2708 * @param {...Mixed} data
2712 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2719 // Alias $j to jQuery for backwards compatibility
2720 // @deprecated since 1.23 Use $ or jQuery instead
2721 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2724 * Log a message to window.console, if possible.
2726 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2727 * also in production mode). Gets console references in each invocation instead of caching the
2728 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2731 * @param {string} topic Stream name passed by mw.track
2732 * @param {Object} data Data passed by mw.track
2733 * @param {Error} [data.exception]
2734 * @param {string} data.source Error source
2735 * @param {string} [data.module] Name of module which caused the error
2737 function logError( topic
, data
) {
2738 /* eslint-disable no-console */
2741 source
= data
.source
,
2742 module
= data
.module
,
2743 console
= window
.console
;
2745 if ( console
&& console
.log
) {
2746 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2748 msg
+= ' in module ' + module
;
2750 msg
+= ( e
? ':' : '.' );
2753 // If we have an exception object, log it to the error channel to trigger
2754 // proper stacktraces in browsers that support it. No fallback as we have
2755 // no browsers that don't support error(), but do support log().
2756 if ( e
&& console
.error
) {
2757 console
.error( String( e
), e
);
2760 /* eslint-enable no-console */
2763 // Subscribe to error streams
2764 mw
.trackSubscribe( 'resourceloader.exception', logError
);
2765 mw
.trackSubscribe( 'resourceloader.assert', logError
);
2768 * Fired when all modules associated with the page have finished loading.
2770 * @event resourceloader_loadEnd
2774 var loading
= $.grep( mw
.loader
.getModuleNames(), function ( module
) {
2775 return mw
.loader
.getState( module
) === 'loading';
2777 // We only need a callback, not any actual module. First try a single using()
2778 // for all loading modules. If one fails, fall back to tracking each module
2779 // separately via $.when(), this is expensive.
2780 loading
= mw
.loader
.using( loading
).then( null, function () {
2781 var all
= $.map( loading
, function ( module
) {
2782 return mw
.loader
.using( module
).then( null, function () {
2783 return $.Deferred().resolve();
2786 return $.when
.apply( $, all
);
2788 loading
.then( function () {
2789 /* global mwPerformance */
2790 mwPerformance
.mark( 'mwLoadEnd' );
2791 mw
.hook( 'resourceloader.loadEnd' ).fire();
2795 // Attach to window and globally alias
2796 window
.mw
= window
.mediaWiki
= mw
;