fbe8af2d62f0a5e483a962a5c9c10dd0db925e9a
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-US/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
) {
93 if ( arguments
.length
> 1 ) {
94 if ( typeof selection
!== 'string' ) {
97 setGlobalMapValue( this, selection
, value
);
100 if ( typeof selection
=== 'object' ) {
101 for ( s
in selection
) {
102 setGlobalMapValue( this, s
, selection
[ s
] );
112 * Alias property to the global object.
116 * @param {mw.Map} map
117 * @param {string} key
118 * @param {Mixed} value
120 function setGlobalMapValue( map
, key
, value
) {
121 map
.values
[ key
] = value
;
126 // Deprecation notice for mw.config globals (T58550, T72470)
127 map
=== mw
.config
&& 'Use mw.config instead.'
135 * Get the value of one or more keys.
137 * If called with no arguments, all values are returned.
139 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
140 * @param {Mixed} [fallback=null] Value for keys that don't exist.
141 * @return {Mixed|Object|null} If selection was a string, returns the value,
142 * If selection was an array, returns an object of key/values.
143 * If no selection is passed, a new object with all key/values is returned.
145 get: function ( selection
, fallback
) {
147 fallback
= arguments
.length
> 1 ? fallback
: null;
149 if ( Array
.isArray( selection
) ) {
151 for ( i
= 0; i
< selection
.length
; i
++ ) {
152 if ( typeof selection
[ i
] === 'string' ) {
153 results
[ selection
[ i
] ] = hasOwn
.call( this.values
, selection
[ i
] ) ?
154 this.values
[ selection
[ i
] ] :
161 if ( typeof selection
=== 'string' ) {
162 return hasOwn
.call( this.values
, selection
) ?
163 this.values
[ selection
] :
167 if ( selection
=== undefined ) {
169 for ( i
in this.values
) {
170 results
[ i
] = this.values
[ i
];
175 // Invalid selection key
180 * Set one or more key/value pairs.
182 * @param {string|Object} selection Key to set value for, or object mapping keys to values
183 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
184 * @return {boolean} True on success, false on failure
186 set: function ( selection
, value
) {
188 // Use `arguments.length` because `undefined` is also a valid value.
189 if ( arguments
.length
> 1 ) {
190 if ( typeof selection
!== 'string' ) {
193 this.values
[ selection
] = value
;
196 if ( typeof selection
=== 'object' ) {
197 for ( s
in selection
) {
198 this.values
[ s
] = selection
[ s
];
206 * Check if one or more keys exist.
208 * @param {Mixed} selection Key or array of keys to check
209 * @return {boolean} True if the key(s) exist
211 exists: function ( selection
) {
213 if ( Array
.isArray( selection
) ) {
214 for ( i
= 0; i
< selection
.length
; i
++ ) {
215 if ( typeof selection
[ i
] !== 'string' || !hasOwn
.call( this.values
, selection
[ i
] ) ) {
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
) );
308 // eslint-disable-next-line valid-jsdoc
310 * Add (does not replace) parameters for `$N` placeholder values.
312 * @param {Array} parameters
315 params: function ( parameters
) {
317 for ( i
= 0; i
< parameters
.length
; i
++ ) {
318 this.parameters
.push( parameters
[ i
] );
324 * Convert message object to its string form based on current format.
326 * @return {string} Message as a string in the current form, or `<key>` if key
329 toString: function () {
332 if ( !this.exists() ) {
333 // Use ⧼key⧽ as text if key does not exist
334 // Err on the side of safety, ensure that the output
335 // is always html safe in the event the message key is
336 // missing, since in that case its highly likely the
337 // message key is user-controlled.
338 // '⧼' is used instead of '<' to side-step any
339 // double-escaping issues.
340 // (Keep synchronised with Message::toString() in PHP.)
341 return '⧼' + mw
.html
.escape( this.key
) + '⧽';
344 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
345 text
= this.parser();
348 if ( this.format
=== 'escaped' ) {
349 text
= this.parser();
350 text
= mw
.html
.escape( text
);
357 * Change format to 'parse' and convert message to string
359 * If jqueryMsg is loaded, this parses the message text from wikitext
360 * (where supported) to HTML
362 * Otherwise, it is equivalent to plain.
364 * @return {string} String form of parsed message
367 this.format
= 'parse';
368 return this.toString();
372 * Change format to 'plain' and convert message to string
374 * This substitutes parameters, but otherwise does not change the
377 * @return {string} String form of plain message
380 this.format
= 'plain';
381 return this.toString();
385 * Change format to 'text' and convert message to string
387 * If jqueryMsg is loaded, {{-transformation is done where supported
388 * (such as {{plural:}}, {{gender:}}, {{int:}}).
390 * Otherwise, it is equivalent to plain
392 * @return {string} String form of text message
395 this.format
= 'text';
396 return this.toString();
400 * Change the format to 'escaped' and convert message to string
402 * This is equivalent to using the 'text' format (see #text), then
403 * HTML-escaping the output.
405 * @return {string} String form of html escaped message
407 escaped: function () {
408 this.format
= 'escaped';
409 return this.toString();
413 * Check if a message exists
418 exists: function () {
419 return this.map
.exists( this.key
);
425 /* eslint-disable no-console */
426 log
= ( function () {
428 * Write a verbose message to the browser's console in debug mode.
430 * This method is mainly intended for verbose logging. It is a no-op in production mode.
431 * In ResourceLoader debug mode, it will use the browser's console if available, with
432 * fallback to creating a console interface in the DOM and logging messages there.
434 * See {@link mw.log} for other logging methods.
437 * @param {...string} msg Messages to output to console.
439 var log = function () {},
440 console
= window
.console
;
442 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
443 // when adding or removing mw.log methods below!
446 * Collection of methods to help log messages to the console.
453 * Write a message to the browser console's warning channel.
455 * This method is a no-op in browsers that don't implement the Console API.
457 * @param {...string} msg Messages to output to console
459 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
460 Function
.prototype.bind
.call( console
.warn
, console
) :
464 * Write a message to the browser console's error channel.
466 * Most browsers also print a stacktrace when calling this method if the
467 * argument is an Error object.
469 * This method is a no-op in browsers that don't implement the Console API.
472 * @param {Error|...string} msg Messages to output to console
474 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
475 Function
.prototype.bind
.call( console
.error
, console
) :
479 * Create a property on a host object that, when accessed, will produce
480 * a deprecation warning in the console.
482 * @param {Object} obj Host object of deprecated property
483 * @param {string} key Name of property to create in `obj`
484 * @param {Mixed} val The value this property should return when accessed
485 * @param {string} [msg] Optional text to include in the deprecation message
486 * @param {string} [logName=key] Optional custom name for the feature.
487 * This is used instead of `key` in the message and `mw.deprecate` tracking.
489 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
491 } : function ( obj
, key
, val
, msg
, logName
) {
492 var logged
= new StringSet();
493 logName
= logName
|| key
;
494 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
495 function uniqueTrace() {
496 var trace
= new Error().stack
;
497 if ( logged
.has( trace
) ) {
503 // Support: Safari 5.0
504 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
505 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
507 Object
.defineProperty( obj
, key
, {
511 if ( uniqueTrace() ) {
512 mw
.track( 'mw.deprecate', logName
);
517 set: function ( newVal
) {
518 if ( uniqueTrace() ) {
519 mw
.track( 'mw.deprecate', logName
);
532 /* eslint-enable no-console */
538 redefineFallbacksForTest: function () {
539 if ( !window
.QUnit
) {
540 throw new Error( 'Reset not allowed outside unit tests' );
546 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
548 * On browsers that implement the Navigation Timing API, this function will produce floating-point
549 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
550 * it will fall back to using `Date`.
552 * @return {number} Current time
555 // mwNow is defined in startup.js
558 * Format a string. Replace $1, $2 ... $N with positional arguments.
560 * Used by Message#parser().
563 * @param {string} formatString Format string
564 * @param {...Mixed} parameters Values for $N replacements
565 * @return {string} Formatted string
567 format: function ( formatString
) {
568 var parameters
= slice
.call( arguments
, 1 );
569 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
570 var index
= parseInt( match
, 10 ) - 1;
571 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
576 * Track an analytic event.
578 * This method provides a generic means for MediaWiki JavaScript code to capture state
579 * information for analysis. Each logged event specifies a string topic name that describes
580 * the kind of event that it is. Topic names consist of dot-separated path components,
581 * arranged from most general to most specific. Each path component should have a clear and
582 * well-defined purpose.
584 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
585 * events that match their subcription, including those that fired before the handler was
588 * @param {string} topic Topic name
589 * @param {Object} [data] Data describing the event, encoded as an object
591 track: function ( topic
, data
) {
592 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
593 trackCallbacks
.fire( trackQueue
);
597 * Register a handler for subset of analytic events, specified by topic.
599 * Handlers will be called once for each tracked event, including any events that fired before the
600 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
601 * the exact time at which the event fired, a string 'topic' property naming the event, and a
602 * 'data' property which is an object of event-specific data. The event topic and event data are
603 * also passed to the callback as the first and second arguments, respectively.
605 * @param {string} topic Handle events whose name starts with this string prefix
606 * @param {Function} callback Handler to call for each matching tracked event
607 * @param {string} callback.topic
608 * @param {Object} [callback.data]
610 trackSubscribe: function ( topic
, callback
) {
612 function handler( trackQueue
) {
614 for ( ; seen
< trackQueue
.length
; seen
++ ) {
615 event
= trackQueue
[ seen
];
616 if ( event
.topic
.indexOf( topic
) === 0 ) {
617 callback
.call( event
, event
.topic
, event
.data
);
622 trackHandlers
.push( [ handler
, callback
] );
624 trackCallbacks
.add( handler
);
628 * Stop handling events for a particular handler
630 * @param {Function} callback
632 trackUnsubscribe: function ( callback
) {
633 trackHandlers
= trackHandlers
.filter( function ( fns
) {
634 if ( fns
[ 1 ] === callback
) {
635 trackCallbacks
.remove( fns
[ 0 ] );
636 // Ensure the tuple is removed to avoid holding on to closures
643 // Expose Map constructor
646 // Expose Message constructor
650 * Map of configuration values.
652 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
655 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
656 * global `window` object.
658 * @property {mw.Map} config
660 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
664 * Empty object for third-party libraries, for cases where you don't
665 * want to add a new global, or the global is bad and needs containment
673 * Access container for deprecated functionality that can be moved from
674 * from their legacy location and attached to this object (e.g. a global
675 * function that is deprecated and as stop-gap can be exposed through here).
677 * This was reserved for future use but never ended up being used.
679 * @deprecated since 1.22 Let deprecated identifiers keep their original name
680 * and use mw.log#deprecate to create an access container for tracking.
686 * Store for messages.
693 * Store for templates associated with a module.
697 templates
: new Map(),
700 * Get a message object.
702 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
705 * @param {string} key Key of message to get
706 * @param {...Mixed} parameters Values for $N replacements
707 * @return {mw.Message}
709 message: function ( key
) {
710 var parameters
= slice
.call( arguments
, 1 );
711 return new Message( mw
.messages
, key
, parameters
);
715 * Get a message string using the (default) 'text' format.
717 * Shortcut for `mw.message( key, parameters... ).text()`.
720 * @param {string} key Key of message to get
721 * @param {...Mixed} parameters Values for $N replacements
725 return mw
.message
.apply( mw
.message
, arguments
).toString();
732 * Client for ResourceLoader server end point.
734 * This client is in charge of maintaining the module registry and state
735 * machine, initiating network (batch) requests for loading modules, as
736 * well as dependency resolution and execution of source code.
738 * For more information, refer to
739 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
744 loader
: ( function () {
747 * Fired via mw.track on various resource loading errors.
749 * @event resourceloader_exception
750 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
751 * object, but in theory module code could manually throw something else, and that
752 * might also end up here.
753 * @param {string} [module] Name of the module which caused the error. Omitted if the
754 * error is not module-related or the module cannot be easily identified due to
756 * @param {string} source Source of the error. Possible values:
758 * - style: stylesheet error (only affects old IE where a special style loading method
760 * - load-callback: exception thrown by user callback
761 * - module-execute: exception thrown by module code
762 * - resolve: failed to sort dependencies for a module in mw.loader.load
763 * - store-eval: could not evaluate module code cached in localStorage
764 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
765 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
766 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
770 * Fired via mw.track on resource loading error conditions.
772 * @event resourceloader_assert
773 * @param {string} source Source of the error. Possible values:
775 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
776 * bug; see <https://phabricator.wikimedia.org/T59567> for details
780 * Mapping of registered modules.
782 * See #implement and #execute for exact details on support for script, style and messages.
788 * // From mw.loader.register()
789 * 'version': '########' (hash)
790 * 'dependencies': ['required.foo', 'bar.also', ...]
791 * 'group': 'somegroup', (or) null
792 * 'source': 'local', (or) 'anotherwiki'
793 * 'skip': 'return !!window.Example', (or) null
794 * 'module': export Object
796 * // Set from execute() or mw.loader.state()
797 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
799 * // Optionally added at run-time by mw.loader.implement()
801 * 'script': closure, array of urls, or string
802 * 'style': { ... } (see #execute)
803 * 'messages': { 'key': 'value', ... }
810 * The module is known to the system but not yet required.
811 * Meta data is registered via mw.loader#register. Calls to that method are
812 * generated server-side by the startup module.
814 * The module was required through mw.loader (either directly or as dependency of
815 * another module). The client will fetch module contents from the server.
816 * The contents are then stashed in the registry via mw.loader#implement.
818 * The module has been loaded from the server and stashed via mw.loader#implement.
819 * If the module has no more dependencies in-flight, the module will be executed
820 * immediately. Otherwise execution is deferred, controlled via #handlePending.
822 * The module is being executed.
824 * The module has been successfully executed.
826 * The module (or one of its dependencies) produced an error during execution.
828 * The module was registered client-side and requested, but the server denied knowledge
829 * of the module's existence.
835 // Mapping of sources, keyed by source-id, values are strings.
840 // 'sourceId': 'http://example.org/w/load.php'
845 // For queueModuleScript()
846 handlingPendingRequests
= false,
847 pendingRequests
= [],
849 // List of modules to be loaded
853 * List of callback jobs waiting for modules to be ready.
855 * Jobs are created by #enqueue() and run by #handlePending().
857 * Typically when a job is created for a module, the job's dependencies contain
858 * both the required module and all its recursive dependencies.
863 * 'dependencies': [ module names ],
864 * 'ready': Function callback
865 * 'error': Function callback
868 * @property {Object[]} jobs
874 * For #addEmbeddedCSS() and #addLink()
877 * @property {HTMLElement|null} marker
879 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
881 // For addEmbeddedCSS()
883 cssBufferTimer
= null,
885 rAF
= window
.requestAnimationFrame
|| setTimeout
;
888 * Create a new style element and add it to the DOM.
891 * @param {string} text CSS text
892 * @param {Node|null} [nextNode] The element where the style tag
893 * should be inserted before
894 * @return {HTMLElement} Reference to the created style element
896 function newStyleTag( text
, nextNode
) {
897 var el
= document
.createElement( 'style' );
898 el
.appendChild( document
.createTextNode( text
) );
899 if ( nextNode
&& nextNode
.parentNode
) {
900 nextNode
.parentNode
.insertBefore( el
, nextNode
);
902 document
.head
.appendChild( el
);
908 * Add a bit of CSS text to the current browser page.
910 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
911 * or create a new one based on whether the given `cssText` is safe for extension.
914 * @param {string} [cssText=cssBuffer] If called without cssText,
915 * the internal buffer will be inserted instead.
916 * @param {Function} [callback]
918 function addEmbeddedCSS( cssText
, callback
) {
919 function fireCallbacks() {
921 oldCallbacks
= cssCallbacks
;
922 // Reset cssCallbacks variable so it's not polluted by any calls to
923 // addEmbeddedCSS() from one of the callbacks (T105973)
925 for ( i
= 0; i
< oldCallbacks
.length
; i
++ ) {
931 cssCallbacks
.push( callback
);
934 // Yield once before creating the <style> tag. This lets multiple stylesheets
935 // accumulate into one buffer, allowing us to reduce how often new stylesheets
936 // are inserted in the browser. Appending a stylesheet and waiting for the
937 // browser to repaint is fairly expensive. (T47810)
939 // Don't extend the buffer if the item needs its own stylesheet.
940 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
941 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
942 // Linebreak for somewhat distinguishable sections
943 cssBuffer
+= '\n' + cssText
;
944 if ( !cssBufferTimer
) {
945 cssBufferTimer
= rAF( function () {
946 // Wrap in anonymous function that takes no arguments
947 // Support: Firefox < 13
948 // Firefox 12 has non-standard behaviour of passing a number
949 // as first argument to a setTimeout callback.
950 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
957 // This is a scheduled flush for the buffer
959 cssBufferTimer
= null;
964 newStyleTag( cssText
, marker
);
971 * @param {Array} modules List of module names
972 * @return {string} Hash of concatenated version hashes.
974 function getCombinedVersion( modules
) {
975 var hashes
= modules
.map( function ( module
) {
976 return registry
[ module
].version
;
978 return fnv132( hashes
.join( '' ) );
982 * Determine whether all dependencies are in state 'ready', which means we may
983 * execute the module or job now.
986 * @param {Array} modules Names of modules to be checked
987 * @return {boolean} True if all modules are in state 'ready', false otherwise
989 function allReady( modules
) {
991 for ( i
= 0; i
< modules
.length
; i
++ ) {
992 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
1000 * Determine whether all dependencies are in state 'ready', which means we may
1001 * execute the module or job now.
1004 * @param {Array} modules Names of modules to be checked
1005 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1007 function anyFailed( modules
) {
1009 for ( i
= 0; i
< modules
.length
; i
++ ) {
1010 state
= mw
.loader
.getState( modules
[ i
] );
1011 if ( state
=== 'error' || state
=== 'missing' ) {
1019 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1020 * pending jobs and modules that depend upon this module. If the given module failed,
1021 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1022 * all jobs/modules now having their dependencies satisfied.
1024 * Jobs that depend on a failed module, will have their error callback ran (if any).
1027 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1029 function handlePending( module
) {
1030 var j
, job
, hasErrors
, m
, stateChange
;
1032 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1033 // If the current module failed, mark all dependent modules also as failed.
1034 // Iterate until steady-state to propagate the error state upwards in the
1037 stateChange
= false;
1038 for ( m
in registry
) {
1039 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1040 if ( anyFailed( registry
[ m
].dependencies
) ) {
1041 registry
[ m
].state
= 'error';
1046 } while ( stateChange
);
1049 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1050 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1051 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1052 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1053 // All dependencies satisfied, or some have errors
1055 jobs
.splice( j
, 1 );
1059 if ( typeof job
.error
=== 'function' ) {
1060 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1063 if ( typeof job
.ready
=== 'function' ) {
1068 // A user-defined callback raised an exception.
1069 // Swallow it to protect our state machine!
1070 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1075 if ( registry
[ module
].state
=== 'ready' ) {
1076 // The current module became 'ready'. Set it in the module store, and recursively execute all
1077 // dependent modules that are loaded and now have all dependencies satisfied.
1078 mw
.loader
.store
.set( module
, registry
[ module
] );
1079 for ( m
in registry
) {
1080 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1088 * Resolve dependencies and detect circular references.
1091 * @param {string} module Name of the top-level module whose dependencies shall be
1092 * resolved and sorted.
1093 * @param {Array} resolved Returns a topological sort of the given module and its
1094 * dependencies, such that later modules depend on earlier modules. The array
1095 * contains the module names. If the array contains already some module names,
1096 * this function appends its result to the pre-existing array.
1097 * @param {StringSet} [unresolved] Used to track the current dependency
1098 * chain, and to report loops in the dependency graph.
1099 * @throws {Error} If any unregistered module or a dependency loop is encountered
1101 function sortDependencies( module
, resolved
, unresolved
) {
1104 if ( !hasOwn
.call( registry
, module
) ) {
1105 throw new Error( 'Unknown dependency: ' + module
);
1108 if ( registry
[ module
].skip
!== null ) {
1109 // eslint-disable-next-line no-new-func
1110 skip
= new Function( registry
[ module
].skip
);
1111 registry
[ module
].skip
= null;
1113 registry
[ module
].skipped
= true;
1114 registry
[ module
].dependencies
= [];
1115 registry
[ module
].state
= 'ready';
1116 handlePending( module
);
1121 if ( resolved
.indexOf( module
) !== -1 ) {
1122 // Module already resolved; nothing to do
1125 // Create unresolved if not passed in
1126 if ( !unresolved
) {
1127 unresolved
= new StringSet();
1129 // Tracks down dependencies
1130 deps
= registry
[ module
].dependencies
;
1131 for ( i
= 0; i
< deps
.length
; i
++ ) {
1132 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
1133 if ( unresolved
.has( deps
[ i
] ) ) {
1134 throw new Error( mw
.format(
1135 'Circular reference detected: $1 -> $2',
1141 unresolved
.add( module
);
1142 sortDependencies( deps
[ i
], resolved
, unresolved
);
1145 resolved
.push( module
);
1149 * Get names of module that a module depends on, in their proper dependency order.
1152 * @param {string[]} modules Array of string module names
1153 * @return {Array} List of dependencies, including 'module'.
1154 * @throws {Error} If an unregistered module or a dependency loop is encountered
1156 function resolve( modules
) {
1157 var i
, resolved
= [];
1158 for ( i
= 0; i
< modules
.length
; i
++ ) {
1159 sortDependencies( modules
[ i
], resolved
);
1165 * Like #resolve(), except it will silently ignore modules that
1166 * are missing or have missing dependencies.
1169 * @param {string[]} modules Array of string module names
1170 * @return {Array} List of dependencies.
1172 function resolveStubbornly( modules
) {
1173 var i
, saved
, resolved
= [];
1174 for ( i
= 0; i
< modules
.length
; i
++ ) {
1175 saved
= resolved
.slice();
1177 sortDependencies( modules
[ i
], resolved
);
1179 // This module is unknown or has unknown dependencies.
1180 // Undo any incomplete resolutions made and keep going.
1182 mw
.track( 'resourceloader.exception', {
1192 * Load and execute a script.
1195 * @param {string} src URL to script, will be used as the src attribute in the script tag
1196 * @param {Function} [callback] Callback to run after request resolution
1198 function addScript( src
, callback
) {
1199 var script
= document
.createElement( 'script' );
1201 script
.onload
= script
.onerror = function () {
1202 if ( script
.parentNode
) {
1203 script
.parentNode
.removeChild( script
);
1211 document
.head
.appendChild( script
);
1215 * Queue the loading and execution of a script for a particular module.
1218 * @param {string} src URL of the script
1219 * @param {string} moduleName Name of currently executing module
1220 * @param {Function} callback Callback to run after addScript() resolution
1222 function queueModuleScript( src
, moduleName
, callback
) {
1223 pendingRequests
.push( function () {
1224 if ( hasOwn
.call( registry
, moduleName
) ) {
1225 // Emulate runScript() part of execute()
1226 window
.require
= mw
.loader
.require
;
1227 window
.module
= registry
[ moduleName
].module
;
1229 addScript( src
, function () {
1230 // 'module.exports' should not persist after the file is executed to
1231 // avoid leakage to unrelated code. 'require' should be kept, however,
1232 // as asynchronous access to 'require' is allowed and expected. (T144879)
1233 delete window
.module
;
1235 // Start the next one (if any)
1236 if ( pendingRequests
[ 0 ] ) {
1237 pendingRequests
.shift()();
1239 handlingPendingRequests
= false;
1243 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1244 handlingPendingRequests
= true;
1245 pendingRequests
.shift()();
1250 * Utility function for execute()
1253 * @param {string} [media] Media attribute
1254 * @param {string} url URL
1256 function addLink( media
, url
) {
1257 var el
= document
.createElement( 'link' );
1259 el
.rel
= 'stylesheet';
1260 if ( media
&& media
!== 'all' ) {
1263 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1264 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1267 if ( marker
&& marker
.parentNode
) {
1268 marker
.parentNode
.insertBefore( el
, marker
);
1270 document
.head
.appendChild( el
);
1275 * Executes a loaded module, making it ready to use
1278 * @param {string} module Module name to execute
1280 function execute( module
) {
1281 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1282 cssHandlesRegistered
= false;
1284 if ( !hasOwn
.call( registry
, module
) ) {
1285 throw new Error( 'Module has not been registered yet: ' + module
);
1287 if ( registry
[ module
].state
!== 'loaded' ) {
1288 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1291 registry
[ module
].state
= 'executing';
1293 runScript = function () {
1294 var script
, markModuleReady
, nestedAddScript
;
1296 script
= registry
[ module
].script
;
1297 markModuleReady = function () {
1298 registry
[ module
].state
= 'ready';
1299 handlePending( module
);
1301 nestedAddScript = function ( arr
, callback
, i
) {
1302 // Recursively call queueModuleScript() in its own callback
1303 // for each element of arr.
1304 if ( i
>= arr
.length
) {
1305 // We're at the end of the array
1310 queueModuleScript( arr
[ i
], module
, function () {
1311 nestedAddScript( arr
, callback
, i
+ 1 );
1316 if ( Array
.isArray( script
) ) {
1317 nestedAddScript( script
, markModuleReady
, 0 );
1318 } else if ( typeof script
=== 'function' ) {
1319 // Pass jQuery twice so that the signature of the closure which wraps
1320 // the script can bind both '$' and 'jQuery'.
1321 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1324 } else if ( typeof script
=== 'string' ) {
1325 // Site and user modules are legacy scripts that run in the global scope.
1326 // This is transported as a string instead of a function to avoid needing
1327 // to use string manipulation to undo the function wrapper.
1328 $.globalEval( script
);
1332 // Module without script
1336 // Use mw.track instead of mw.log because these errors are common in production mode
1337 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1338 registry
[ module
].state
= 'error';
1339 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1340 handlePending( module
);
1344 // Add localizations to message system
1345 if ( registry
[ module
].messages
) {
1346 mw
.messages
.set( registry
[ module
].messages
);
1349 // Initialise templates
1350 if ( registry
[ module
].templates
) {
1351 mw
.templates
.set( module
, registry
[ module
].templates
);
1354 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1357 checkCssHandles = function () {
1358 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1359 // one of the cssHandles is fired while we're still creating more handles.
1360 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1361 if ( module
=== 'user' ) {
1362 // Implicit dependency on the site module. Not real dependency because
1363 // it should run after 'site' regardless of whether it succeeds or fails.
1364 mw
.loader
.using( [ 'site' ] ).always( runScript
);
1368 runScript
= undefined; // Revoke
1371 cssHandle = function () {
1372 var check
= checkCssHandles
;
1374 return function () {
1378 check
= undefined; // Revoke
1384 // Process styles (see also mw.loader.implement)
1385 // * back-compat: { <media>: css }
1386 // * back-compat: { <media>: [url, ..] }
1387 // * { "css": [css, ..] }
1388 // * { "url": { <media>: [url, ..] } }
1389 if ( registry
[ module
].style
) {
1390 for ( key
in registry
[ module
].style
) {
1391 value
= registry
[ module
].style
[ key
];
1394 if ( key
!== 'url' && key
!== 'css' ) {
1395 // Backwards compatibility, key is a media-type
1396 if ( typeof value
=== 'string' ) {
1397 // back-compat: { <media>: css }
1398 // Ignore 'media' because it isn't supported (nor was it used).
1399 // Strings are pre-wrapped in "@media". The media-type was just ""
1400 // (because it had to be set to something).
1401 // This is one of the reasons why this format is no longer used.
1402 addEmbeddedCSS( value
, cssHandle() );
1404 // back-compat: { <media>: [url, ..] }
1410 // Array of css strings in key 'css',
1411 // or back-compat array of urls from media-type
1412 if ( Array
.isArray( value
) ) {
1413 for ( i
= 0; i
< value
.length
; i
++ ) {
1414 if ( key
=== 'bc-url' ) {
1415 // back-compat: { <media>: [url, ..] }
1416 addLink( media
, value
[ i
] );
1417 } else if ( key
=== 'css' ) {
1418 // { "css": [css, ..] }
1419 addEmbeddedCSS( value
[ i
], cssHandle() );
1422 // Not an array, but a regular object
1423 // Array of urls inside media-type key
1424 } else if ( typeof value
=== 'object' ) {
1425 // { "url": { <media>: [url, ..] } }
1426 for ( media
in value
) {
1427 urls
= value
[ media
];
1428 for ( i
= 0; i
< urls
.length
; i
++ ) {
1429 addLink( media
, urls
[ i
] );
1437 cssHandlesRegistered
= true;
1442 * Add one or more modules to the module load queue.
1447 * @param {string|string[]} dependencies Module name or array of string module names
1448 * @param {Function} [ready] Callback to execute when all dependencies are ready
1449 * @param {Function} [error] Callback to execute when any dependency fails
1451 function enqueue( dependencies
, ready
, error
) {
1452 // Allow calling by single module name
1453 if ( typeof dependencies
=== 'string' ) {
1454 dependencies
= [ dependencies
];
1457 // Add ready and error callbacks if they were given
1458 if ( ready
!== undefined || error
!== undefined ) {
1460 // Narrow down the list to modules that are worth waiting for
1461 dependencies
: dependencies
.filter( function ( module
) {
1462 var state
= mw
.loader
.getState( module
);
1463 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1470 dependencies
.forEach( function ( module
) {
1471 var state
= mw
.loader
.getState( module
);
1472 // Only queue modules that are still in the initial 'registered' state
1473 // (not ones already loading, ready or error).
1474 if ( state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1475 // Private modules must be embedded in the page. Don't bother queuing
1476 // these as the server will deny them anyway (T101806).
1477 if ( registry
[ module
].group
=== 'private' ) {
1478 registry
[ module
].state
= 'error';
1479 handlePending( module
);
1482 queue
.push( module
);
1489 function sortQuery( o
) {
1498 for ( key
= 0; key
< a
.length
; key
++ ) {
1499 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1505 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1506 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1508 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1509 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1511 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1512 * because its implementation needs to keep track of potential string size in order
1513 * to decide when to split the requests due to url size.
1516 * @param {Object} moduleMap Module map
1518 * @return {string} return.str Module query string
1519 * @return {Array} return.list List of module names in matching order
1521 function buildModulesString( moduleMap
) {
1526 function restore( suffix
) {
1530 for ( prefix
in moduleMap
) {
1531 p
= prefix
=== '' ? '' : prefix
+ '.';
1532 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1533 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1536 str
: str
.join( '|' ),
1542 * Resolve indexed dependencies.
1544 * ResourceLoader uses an optimization to save space which replaces module names in
1545 * dependency lists with the index of that module within the array of module
1546 * registration data if it exists. The benefit is a significant reduction in the data
1547 * size of the startup module. This function changes those dependency lists back to
1548 * arrays of strings.
1551 * @param {Array} modules Modules array
1553 function resolveIndexedDependencies( modules
) {
1555 function resolveIndex( dep
) {
1556 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1558 for ( i
= 0; i
< modules
.length
; i
++ ) {
1559 deps
= modules
[ i
][ 2 ];
1561 for ( j
= 0; j
< deps
.length
; j
++ ) {
1562 deps
[ j
] = resolveIndex( deps
[ j
] );
1569 * Create network requests for a batch of modules.
1571 * This is an internal method for #work(). This must not be called directly
1572 * unless the modules are already registered, and no request is in progress,
1573 * and the module state has already been set to `loading`.
1576 * @param {string[]} batch
1578 function batchRequest( batch
) {
1579 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1580 source
, group
, i
, modules
, sourceLoadScript
,
1581 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1582 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1585 * Start the currently drafted request to the server.
1589 function doRequest() {
1590 // Optimisation: Inherit (Object.create), not copy ($.extend)
1591 var query
= Object
.create( currReqBase
),
1592 packed
= buildModulesString( moduleMap
);
1593 query
.modules
= packed
.str
;
1594 // The packing logic can change the effective order, even if the input was
1595 // sorted. As such, the call to getCombinedVersion() must use this
1596 // effective order, instead of currReqModules, as otherwise the combined
1597 // version will not match the hash expected by the server based on
1598 // combining versions from the module query string in-order. (T188076)
1599 query
.version
= getCombinedVersion( packed
.list
);
1600 query
= sortQuery( query
);
1601 addScript( sourceLoadScript
+ '?' + $.param( query
) );
1604 if ( !batch
.length
) {
1608 // Always order modules alphabetically to help reduce cache
1609 // misses for otherwise identical content.
1612 // Query parameters common to all requests
1614 skin
: mw
.config
.get( 'skin' ),
1615 lang
: mw
.config
.get( 'wgUserLanguage' ),
1616 debug
: mw
.config
.get( 'debug' )
1618 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1620 // Split module list by source and by group.
1622 for ( b
= 0; b
< batch
.length
; b
++ ) {
1623 bSource
= registry
[ batch
[ b
] ].source
;
1624 bGroup
= registry
[ batch
[ b
] ].group
;
1625 if ( !hasOwn
.call( splits
, bSource
) ) {
1626 splits
[ bSource
] = {};
1628 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1629 splits
[ bSource
][ bGroup
] = [];
1631 bSourceGroup
= splits
[ bSource
][ bGroup
];
1632 bSourceGroup
.push( batch
[ b
] );
1635 for ( source
in splits
) {
1637 sourceLoadScript
= sources
[ source
];
1639 for ( group
in splits
[ source
] ) {
1641 // Cache access to currently selected list of
1642 // modules for this group from this source.
1643 modules
= splits
[ source
][ group
];
1645 // Query parameters common to requests for this module group
1646 // Optimisation: Inherit (Object.create), not copy ($.extend)
1647 currReqBase
= Object
.create( reqBase
);
1648 // User modules require a user name in the query string.
1649 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1650 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1653 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1654 // > '&modules='.length === 9
1655 // > '&version=1234567'.length === 16
1657 currReqBaseLength
= $.param( currReqBase
).length
+ 25;
1659 // We may need to split up the request to honor the query string length limit,
1660 // so build it piece by piece.
1661 l
= currReqBaseLength
;
1662 moduleMap
= {}; // { prefix: [ suffixes ] }
1663 currReqModules
= [];
1665 for ( i
= 0; i
< modules
.length
; i
++ ) {
1666 // Determine how many bytes this module would add to the query string
1667 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1668 // If lastDotIndex is -1, substr() returns an empty string
1669 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1670 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1671 bytesAdded
= hasOwn
.call( moduleMap
, prefix
) ?
1672 suffix
.length
+ 3 : // '%2C'.length == 3
1673 modules
[ i
].length
+ 3; // '%7C'.length == 3
1675 // If the url would become too long, create a new one, but don't create empty requests
1676 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1677 // Dispatch what we've got...
1679 // .. and start again.
1680 l
= currReqBaseLength
;
1682 currReqModules
= [];
1684 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1686 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1687 moduleMap
[ prefix
] = [];
1690 moduleMap
[ prefix
].push( suffix
);
1691 currReqModules
.push( modules
[ i
] );
1693 // If there's anything left in moduleMap, request that too
1694 if ( currReqModules
.length
) {
1703 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1704 * form of calls to mw.loader#implement().
1705 * @param {Function} cb Callback in case of failure
1706 * @param {Error} cb.err
1708 function asyncEval( implementations
, cb
) {
1709 if ( !implementations
.length
) {
1712 mw
.requestIdleCallback( function () {
1714 $.globalEval( implementations
.join( ';' ) );
1722 * Make a versioned key for a specific module.
1725 * @param {string} module Module name
1726 * @return {string|null} Module key in format '`[name]@[version]`',
1727 * or null if the module does not exist
1729 function getModuleKey( module
) {
1730 return hasOwn
.call( registry
, module
) ?
1731 ( module
+ '@' + registry
[ module
].version
) : null;
1736 * @param {string} key Module name or '`[name]@[version]`'
1739 function splitModuleKey( key
) {
1740 var index
= key
.indexOf( '@' );
1741 if ( index
=== -1 ) {
1748 name
: key
.slice( 0, index
),
1749 version
: key
.slice( index
+ 1 )
1753 /* Public Members */
1756 * The module registry is exposed as an aid for debugging and inspecting page
1757 * state; it is not a public interface for modifying the registry.
1763 moduleRegistry
: registry
,
1766 * @inheritdoc #newStyleTag
1769 addStyleTag
: newStyleTag
,
1772 * Start loading of all queued module dependencies.
1777 var q
, batch
, implementations
, sourceModules
;
1781 // Appends a list of modules from the queue to the batch
1782 for ( q
= 0; q
< queue
.length
; q
++ ) {
1783 // Only load modules which are registered
1784 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1785 // Prevent duplicate entries
1786 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1787 batch
.push( queue
[ q
] );
1788 // Mark registered modules as loading
1789 registry
[ queue
[ q
] ].state
= 'loading';
1794 // Now that the queue has been processed into a batch, clear the queue.
1795 // This MUST happen before we initiate any eval or network request. Otherwise,
1796 // it is possible for a cached script to instantly trigger the same work queue
1797 // again; all before we've cleared it causing each request to include modules
1798 // which are already loaded.
1801 if ( !batch
.length
) {
1805 mw
.loader
.store
.init();
1806 if ( mw
.loader
.store
.enabled
) {
1807 implementations
= [];
1809 batch
= batch
.filter( function ( module
) {
1810 var implementation
= mw
.loader
.store
.get( module
);
1811 if ( implementation
) {
1812 implementations
.push( implementation
);
1813 sourceModules
.push( module
);
1818 asyncEval( implementations
, function ( err
) {
1820 // Not good, the cached mw.loader.implement calls failed! This should
1821 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1822 // Depending on how corrupt the string is, it is likely that some
1823 // modules' implement() succeeded while the ones after the error will
1824 // never run and leave their modules in the 'loading' state forever.
1825 mw
.loader
.store
.stats
.failed
++;
1827 // Since this is an error not caused by an individual module but by
1828 // something that infected the implement call itself, don't take any
1829 // risks and clear everything in this cache.
1830 mw
.loader
.store
.clear();
1832 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1833 // Re-add the failed ones that are still pending back to the batch
1834 failed
= sourceModules
.filter( function ( module
) {
1835 return registry
[ module
].state
=== 'loading';
1837 batchRequest( failed
);
1841 batchRequest( batch
);
1845 * Register a source.
1847 * The #work() method will use this information to split up requests by source.
1849 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1851 * @param {string|Object} id Source ID, or object mapping ids to load urls
1852 * @param {string} loadUrl Url to a load.php end point
1853 * @throws {Error} If source id is already registered
1855 addSource: function ( id
, loadUrl
) {
1857 // Allow multiple additions
1858 if ( typeof id
=== 'object' ) {
1859 for ( source
in id
) {
1860 mw
.loader
.addSource( source
, id
[ source
] );
1865 if ( hasOwn
.call( sources
, id
) ) {
1866 throw new Error( 'source already registered: ' + id
);
1869 sources
[ id
] = loadUrl
;
1873 * Register a module, letting the system know about it and its properties.
1875 * The startup modules contain calls to this method.
1877 * When using multiple module registration by passing an array, dependencies that
1878 * are specified as references to modules within the array will be resolved before
1879 * the modules are registered.
1881 * @param {string|Array} module Module name or array of arrays, each containing
1882 * a list of arguments compatible with this method
1883 * @param {string|number} version Module version hash (falls backs to empty string)
1884 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1885 * @param {string|Array} dependencies One string or array of strings of module
1886 * names on which this module depends.
1887 * @param {string} [group=null] Group which the module is in
1888 * @param {string} [source='local'] Name of the source
1889 * @param {string} [skip=null] Script body of the skip function
1891 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1893 // Allow multiple registration
1894 if ( typeof module
=== 'object' ) {
1895 resolveIndexedDependencies( module
);
1896 for ( i
= 0; i
< module
.length
; i
++ ) {
1897 // module is an array of module names
1898 if ( typeof module
[ i
] === 'string' ) {
1899 mw
.loader
.register( module
[ i
] );
1900 // module is an array of arrays
1901 } else if ( typeof module
[ i
] === 'object' ) {
1902 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1907 if ( hasOwn
.call( registry
, module
) ) {
1908 throw new Error( 'module already registered: ' + module
);
1910 if ( typeof dependencies
=== 'string' ) {
1911 // A single module name
1912 deps
= [ dependencies
];
1913 } else if ( typeof dependencies
=== 'object' ) {
1914 // Array of module names
1915 deps
= dependencies
;
1917 // List the module as registered
1918 registry
[ module
] = {
1919 // Exposed to execute() for mw.loader.implement() closures.
1920 // Import happens via require().
1924 version
: version
!== undefined ? String( version
) : '',
1925 dependencies
: deps
|| [],
1926 group
: typeof group
=== 'string' ? group
: null,
1927 source
: typeof source
=== 'string' ? source
: 'local',
1928 state
: 'registered',
1929 skip
: typeof skip
=== 'string' ? skip
: null
1934 * Implement a module given the components that make up the module.
1936 * When #load() or #using() requests one or more modules, the server
1937 * response contain calls to this function.
1939 * @param {string} module Name of module and current module version. Formatted
1940 * as '`[name]@[version]`". This version should match the requested version
1941 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1942 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1943 * @param {Function|Array|string} [script] Function with module code, list of URLs
1944 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1945 * @param {Object} [style] Should follow one of the following patterns:
1947 * { "css": [css, ..] }
1948 * { "url": { <media>: [url, ..] } }
1950 * And for backwards compatibility (needs to be supported forever due to caching):
1953 * { <media>: [url, ..] }
1955 * The reason css strings are not concatenated anymore is T33676. We now check
1956 * whether it's safe to extend the stylesheet.
1959 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1960 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1962 implement: function ( module
, script
, style
, messages
, templates
) {
1963 var split
= splitModuleKey( module
),
1965 version
= split
.version
;
1966 // Automatically register module
1967 if ( !hasOwn
.call( registry
, name
) ) {
1968 mw
.loader
.register( name
);
1970 // Check for duplicate implementation
1971 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1972 throw new Error( 'module already implemented: ' + name
);
1975 // Without this reset, if there is a version mismatch between the
1976 // requested and received module version, then mw.loader.store would
1977 // cache the response under the requested key. Thus poisoning the cache
1978 // indefinitely with a stale value. (T117587)
1979 registry
[ name
].version
= version
;
1981 // Attach components
1982 registry
[ name
].script
= script
|| null;
1983 registry
[ name
].style
= style
|| null;
1984 registry
[ name
].messages
= messages
|| null;
1985 registry
[ name
].templates
= templates
|| null;
1986 // The module may already have been marked as erroneous
1987 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1988 registry
[ name
].state
= 'loaded';
1989 if ( allReady( registry
[ name
].dependencies
) ) {
1996 * Execute a function as soon as one or more required modules are ready.
1998 * Example of inline dependency on OOjs:
2000 * mw.loader.using( 'oojs', function () {
2001 * OO.compare( [ 1 ], [ 1 ] );
2004 * Example of inline dependency obtained via `require()`:
2006 * mw.loader.using( [ 'mediawiki.util' ], function ( require ) {
2007 * var util = require( 'mediawiki.util' );
2010 * Since MediaWiki 1.23 this also returns a promise.
2012 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
2014 * @param {string|Array} dependencies Module name or array of modules names the
2015 * callback depends on to be ready before executing
2016 * @param {Function} [ready] Callback to execute when all dependencies are ready
2017 * @param {Function} [error] Callback to execute if one or more dependencies failed
2018 * @return {jQuery.Promise} With a `require` function
2020 using: function ( dependencies
, ready
, error
) {
2021 var deferred
= $.Deferred();
2023 // Allow calling with a single dependency as a string
2024 if ( typeof dependencies
=== 'string' ) {
2025 dependencies
= [ dependencies
];
2029 deferred
.done( ready
);
2032 deferred
.fail( error
);
2036 // Resolve entire dependency map
2037 dependencies
= resolve( dependencies
);
2039 return deferred
.reject( e
).promise();
2041 if ( allReady( dependencies
) ) {
2042 // Run ready immediately
2043 deferred
.resolve( mw
.loader
.require
);
2044 } else if ( anyFailed( dependencies
) ) {
2045 // Execute error immediately if any dependencies have errors
2047 new Error( 'One or more dependencies failed to load' ),
2051 // Not all dependencies are ready, add to the load queue
2052 enqueue( dependencies
, function () {
2053 deferred
.resolve( mw
.loader
.require
);
2054 }, deferred
.reject
);
2057 return deferred
.promise();
2061 * Load an external script or one or more modules.
2063 * This method takes a list of unrelated modules. Use cases:
2065 * - A web page will be composed of many different widgets. These widgets independently
2066 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
2067 * have problems, or are no longer known (e.g. cached HTML), the other modules
2068 * should still be loaded.
2069 * - This method is used for preloading, which must not throw. Later code that
2070 * calls #using() will handle the error.
2072 * @param {string|Array} modules Either the name of a module, array of modules,
2073 * or a URL of an external script or style
2074 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2075 * external script or style; acceptable values are "text/css" and
2076 * "text/javascript"; if no type is provided, text/javascript is assumed.
2078 load: function ( modules
, type
) {
2081 // Allow calling with a url or single dependency as a string
2082 if ( typeof modules
=== 'string' ) {
2083 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2084 if ( /^(https?:)?\/?\//.test( modules
) ) {
2085 if ( type
=== 'text/css' ) {
2086 l
= document
.createElement( 'link' );
2087 l
.rel
= 'stylesheet';
2089 document
.head
.appendChild( l
);
2092 if ( type
=== 'text/javascript' || type
=== undefined ) {
2093 addScript( modules
);
2097 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2099 // Called with single module
2100 modules
= [ modules
];
2103 // Filter out top-level modules that are unknown or failed to load before.
2104 filtered
= modules
.filter( function ( module
) {
2105 var state
= mw
.loader
.getState( module
);
2106 return state
!== 'error' && state
!== 'missing';
2108 // Resolve remaining list using the known dependency tree.
2109 // This also filters out modules with unknown dependencies. (T36853)
2110 filtered
= resolveStubbornly( filtered
);
2111 // If all modules are ready, or if any modules have errors, nothing to be done.
2112 if ( allReady( filtered
) || anyFailed( filtered
) ) {
2115 if ( filtered
.length
=== 0 ) {
2118 // Some modules are not yet ready, add to module load queue.
2119 enqueue( filtered
, undefined, undefined );
2123 * Change the state of one or more modules.
2125 * @param {string|Object} module Module name or object of module name/state pairs
2126 * @param {string} state State name
2128 state: function ( module
, state
) {
2131 if ( typeof module
=== 'object' ) {
2132 for ( m
in module
) {
2133 mw
.loader
.state( m
, module
[ m
] );
2137 if ( !hasOwn
.call( registry
, module
) ) {
2138 mw
.loader
.register( module
);
2140 registry
[ module
].state
= state
;
2141 if ( state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
2142 // Make sure pending modules depending on this one get executed if their
2143 // dependencies are now fulfilled!
2144 handlePending( module
);
2149 * Get the version of a module.
2151 * @param {string} module Name of module
2152 * @return {string|null} The version, or null if the module (or its version) is not
2155 getVersion: function ( module
) {
2156 return hasOwn
.call( registry
, module
) ? registry
[ module
].version
: null;
2160 * Get the state of a module.
2162 * @param {string} module Name of module
2163 * @return {string|null} The state, or null if the module (or its state) is not
2166 getState: function ( module
) {
2167 return hasOwn
.call( registry
, module
) ? registry
[ module
].state
: null;
2171 * Get the names of all registered modules.
2175 getModuleNames: function () {
2176 return Object
.keys( registry
);
2180 * Get the exported value of a module.
2182 * This static method is publicly exposed for debugging purposes
2183 * only and must not be used in production code. In production code,
2184 * please use the dynamically provided `require()` function instead.
2186 * In case of lazy-loaded modules via mw.loader#using(), the returned
2187 * Promise provides the function, see #using() for examples.
2191 * @param {string} moduleName Module name
2192 * @return {Mixed} Exported value
2194 require: function ( moduleName
) {
2195 var state
= mw
.loader
.getState( moduleName
);
2197 // Only ready modules can be required
2198 if ( state
!== 'ready' ) {
2199 // Module may've forgotten to declare a dependency
2200 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2203 return registry
[ moduleName
].module
.exports
;
2207 * @inheritdoc mw.inspect#runReports
2210 inspect: function () {
2211 var args
= slice
.call( arguments
);
2212 mw
.loader
.using( 'mediawiki.inspect', function () {
2213 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2218 * On browsers that implement the localStorage API, the module store serves as a
2219 * smart complement to the browser cache. Unlike the browser cache, the module store
2220 * can slice a concatenated response from ResourceLoader into its constituent
2221 * modules and cache each of them separately, using each module's versioning scheme
2222 * to determine when the cache should be invalidated.
2225 * @class mw.loader.store
2228 // Whether the store is in use on this page.
2231 // Modules whose string representation exceeds 100 kB are
2232 // ineligible for storage. See bug T66721.
2233 MODULE_SIZE_MAX
: 100 * 1000,
2235 // The contents of the store, mapping '[name]@[version]' keys
2236 // to module implementations.
2240 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2243 * Construct a JSON-serializable object representing the content of the store.
2245 * @return {Object} Module store contents.
2247 toJSON: function () {
2248 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2252 * Get the localStorage key for the entire module store. The key references
2253 * $wgDBname to prevent clashes between wikis which share a common host.
2255 * @return {string} localStorage item key
2257 getStoreKey: function () {
2258 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2262 * Get a key on which to vary the module cache.
2264 * @return {string} String of concatenated vary conditions.
2266 getVary: function () {
2268 mw
.config
.get( 'skin' ),
2269 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2270 mw
.config
.get( 'wgUserLanguage' )
2275 * Initialize the store.
2277 * Retrieves store from localStorage and (if successfully retrieved) decoding
2278 * the stored JSON value to a plain object.
2280 * The try / catch block is used for JSON & localStorage feature detection.
2281 * See the in-line documentation for Modernizr's localStorage feature detection
2282 * code for a full account of why we need a try / catch:
2283 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2288 if ( mw
.loader
.store
.enabled
!== null ) {
2294 // Disabled because localStorage quotas are tight and (in Firefox's case)
2295 // shared by multiple origins.
2296 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2297 /Firefox|Opera/.test( navigator
.userAgent
) ||
2299 // Disabled by configuration.
2300 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2302 // Clear any previous store to free up space. (T66721)
2303 mw
.loader
.store
.clear();
2304 mw
.loader
.store
.enabled
= false;
2307 if ( mw
.config
.get( 'debug' ) ) {
2308 // Disable module store in debug mode
2309 mw
.loader
.store
.enabled
= false;
2314 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2315 // If we get here, localStorage is available; mark enabled
2316 mw
.loader
.store
.enabled
= true;
2317 data
= JSON
.parse( raw
);
2318 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2319 mw
.loader
.store
.items
= data
.items
;
2323 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2326 if ( raw
=== undefined ) {
2327 // localStorage failed; disable store
2328 mw
.loader
.store
.enabled
= false;
2330 mw
.loader
.store
.update();
2335 * Retrieve a module from the store and update cache hit stats.
2337 * @param {string} module Module name
2338 * @return {string|boolean} Module implementation or false if unavailable
2340 get: function ( module
) {
2343 if ( !mw
.loader
.store
.enabled
) {
2347 key
= getModuleKey( module
);
2348 if ( key
in mw
.loader
.store
.items
) {
2349 mw
.loader
.store
.stats
.hits
++;
2350 return mw
.loader
.store
.items
[ key
];
2352 mw
.loader
.store
.stats
.misses
++;
2357 * Stringify a module and queue it for storage.
2359 * @param {string} module Module name
2360 * @param {Object} descriptor The module's descriptor as set in the registry
2361 * @return {boolean} Module was set
2363 set: function ( module
, descriptor
) {
2366 if ( !mw
.loader
.store
.enabled
) {
2370 key
= getModuleKey( module
);
2373 // Already stored a copy of this exact version
2374 key
in mw
.loader
.store
.items
||
2375 // Module failed to load
2376 descriptor
.state
!== 'ready' ||
2377 // Unversioned, private, or site-/user-specific
2378 !descriptor
.version
||
2379 descriptor
.group
=== 'private' ||
2380 descriptor
.group
=== 'user' ||
2381 // Partial descriptor
2382 // (e.g. skipped module, or style module with state=ready)
2383 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2384 descriptor
.templates
].indexOf( undefined ) !== -1
2392 JSON
.stringify( key
),
2393 typeof descriptor
.script
=== 'function' ?
2394 String( descriptor
.script
) :
2395 JSON
.stringify( descriptor
.script
),
2396 JSON
.stringify( descriptor
.style
),
2397 JSON
.stringify( descriptor
.messages
),
2398 JSON
.stringify( descriptor
.templates
)
2400 // Attempted workaround for a possible Opera bug (bug T59567).
2401 // This regex should never match under sane conditions.
2402 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2403 args
[ 1 ] = 'function' + args
[ 1 ];
2404 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2407 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2411 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2412 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2415 mw
.loader
.store
.items
[ key
] = src
;
2416 mw
.loader
.store
.update();
2421 * Iterate through the module store, removing any item that does not correspond
2422 * (in name and version) to an item in the module registry.
2424 * @return {boolean} Store was pruned
2426 prune: function () {
2429 if ( !mw
.loader
.store
.enabled
) {
2433 for ( key
in mw
.loader
.store
.items
) {
2434 module
= key
.slice( 0, key
.indexOf( '@' ) );
2435 if ( getModuleKey( module
) !== key
) {
2436 mw
.loader
.store
.stats
.expired
++;
2437 delete mw
.loader
.store
.items
[ key
];
2438 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2439 // This value predates the enforcement of a size limit on cached modules.
2440 delete mw
.loader
.store
.items
[ key
];
2447 * Clear the entire module store right now.
2449 clear: function () {
2450 mw
.loader
.store
.items
= {};
2452 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2453 } catch ( ignored
) {}
2457 * Sync in-memory store back to localStorage.
2459 * This function debounces updates. When called with a flush already pending,
2460 * the call is coalesced into the pending update. The call to
2461 * localStorage.setItem will be naturally deferred until the page is quiescent.
2463 * Because localStorage is shared by all pages from the same origin, if multiple
2464 * pages are loaded with different module sets, the possibility exists that
2465 * modules saved by one page will be clobbered by another. But the impact would
2466 * be minor and the problem would be corrected by subsequent page views.
2470 update
: ( function () {
2471 var hasPendingWrite
= false;
2473 function flushWrites() {
2475 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2479 mw
.loader
.store
.prune();
2480 key
= mw
.loader
.store
.getStoreKey();
2482 // Replacing the content of the module store might fail if the new
2483 // contents would exceed the browser's localStorage size limit. To
2484 // avoid clogging the browser with stale data, always remove the old
2485 // value before attempting to set the new one.
2486 localStorage
.removeItem( key
);
2487 data
= JSON
.stringify( mw
.loader
.store
);
2488 localStorage
.setItem( key
, data
);
2490 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2493 hasPendingWrite
= false;
2496 return function () {
2497 if ( !hasPendingWrite
) {
2498 hasPendingWrite
= true;
2499 mw
.requestIdleCallback( flushWrites
);
2508 * HTML construction helper functions
2515 * output = Html.element( 'div', {}, new Html.Raw(
2516 * Html.element( 'img', { src: '<' } )
2518 * mw.log( output ); // <div><img src="<"/></div>
2523 html
: ( function () {
2524 function escapeCallback( s
) {
2541 * Escape a string for HTML.
2543 * Converts special characters to HTML entities.
2545 * mw.html.escape( '< > \' & "' );
2546 * // Returns < > ' & "
2548 * @param {string} s The string to escape
2549 * @return {string} HTML
2551 escape: function ( s
) {
2552 return s
.replace( /['"<>&]/g, escapeCallback
);
2556 * Create an HTML element string, with safe escaping.
2558 * @param {string} name The tag name.
2559 * @param {Object} [attrs] An object with members mapping element names to values
2560 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2562 * - string: Text to be escaped.
2563 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2564 * - this.Raw: The raw value is directly included.
2565 * - this.Cdata: The raw value is directly included. An exception is
2566 * thrown if it contains any illegal ETAGO delimiter.
2567 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2568 * @return {string} HTML
2570 element: function ( name
, attrs
, contents
) {
2571 var v
, attrName
, s
= '<' + name
;
2574 for ( attrName
in attrs
) {
2575 v
= attrs
[ attrName
];
2576 // Convert name=true, to name=name
2580 } else if ( v
=== false ) {
2583 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2586 if ( contents
=== undefined || contents
=== null ) {
2593 switch ( typeof contents
) {
2596 s
+= this.escape( contents
);
2600 // Convert to string
2601 s
+= String( contents
);
2604 if ( contents
instanceof this.Raw
) {
2605 // Raw HTML inclusion
2606 s
+= contents
.value
;
2607 } else if ( contents
instanceof this.Cdata
) {
2609 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2610 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2612 s
+= contents
.value
;
2614 throw new Error( 'mw.html.element: Invalid type of contents' );
2617 s
+= '</' + name
+ '>';
2622 * Wrapper object for raw HTML passed to mw.html.element().
2624 * @class mw.html.Raw
2626 * @param {string} value
2628 Raw: function ( value
) {
2633 * Wrapper object for CDATA element contents passed to mw.html.element()
2635 * @class mw.html.Cdata
2637 * @param {string} value
2639 Cdata: function ( value
) {
2645 // Skeleton user object, extended by the 'mediawiki.user' module.
2652 * @property {mw.Map}
2656 * @property {mw.Map}
2661 // OOUI widgets specific to MediaWiki
2665 * Registry and firing of events.
2667 * MediaWiki has various interface components that are extended, enhanced
2668 * or manipulated in some other way by extensions, gadgets and even
2671 * This framework helps streamlining the timing of when these other
2672 * code paths fire their plugins (instead of using document-ready,
2673 * which can and should be limited to firing only once).
2675 * Features like navigating to other wiki pages, previewing an edit
2676 * and editing itself – without a refresh – can then retrigger these
2677 * hooks accordingly to ensure everything still works as expected.
2681 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2682 * mw.hook( 'wikipage.content' ).fire( $content );
2684 * Handlers can be added and fired for arbitrary event names at any time. The same
2685 * event can be fired multiple times. The last run of an event is memorized
2686 * (similar to `$(document).ready` and `$.Deferred().done`).
2687 * This means if an event is fired, and a handler added afterwards, the added
2688 * function will be fired right away with the last given event data.
2690 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2691 * Thus allowing flexible use and optimal maintainability and authority control.
2692 * You can pass around the `add` and/or `fire` method to another piece of code
2693 * without it having to know the event name (or `mw.hook` for that matter).
2695 * var h = mw.hook( 'bar.ready' );
2696 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2698 * Note: Events are documented with an underscore instead of a dot in the event
2699 * name due to jsduck not supporting dots in that position.
2703 hook
: ( function () {
2707 * Create an instance of mw.hook.
2711 * @param {string} name Name of hook.
2714 return function ( name
) {
2715 var list
= hasOwn
.call( lists
, name
) ?
2717 lists
[ name
] = $.Callbacks( 'memory' );
2721 * Register a hook handler
2723 * @param {...Function} handler Function to bind.
2729 * Unregister a hook handler
2731 * @param {...Function} handler Function to unbind.
2734 remove
: list
.remove
,
2736 // eslint-disable-next-line valid-jsdoc
2740 * @param {...Mixed} data
2744 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2751 // Alias $j to jQuery for backwards compatibility
2752 // @deprecated since 1.23 Use $ or jQuery instead
2753 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2756 * Log a message to window.console, if possible.
2758 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2759 * also in production mode). Gets console references in each invocation instead of caching the
2760 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2763 * @param {string} topic Stream name passed by mw.track
2764 * @param {Object} data Data passed by mw.track
2765 * @param {Error} [data.exception]
2766 * @param {string} data.source Error source
2767 * @param {string} [data.module] Name of module which caused the error
2769 function logError( topic
, data
) {
2770 /* eslint-disable no-console */
2773 source
= data
.source
,
2774 module
= data
.module
,
2775 console
= window
.console
;
2777 if ( console
&& console
.log
) {
2778 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2780 msg
+= ' in module ' + module
;
2782 msg
+= ( e
? ':' : '.' );
2785 // If we have an exception object, log it to the warning channel to trigger
2786 // proper stacktraces in browsers that support it.
2787 if ( e
&& console
.warn
) {
2791 /* eslint-enable no-console */
2794 // Subscribe to error streams
2795 mw
.trackSubscribe( 'resourceloader.exception', logError
);
2796 mw
.trackSubscribe( 'resourceloader.assert', logError
);
2799 * Fired when all modules associated with the page have finished loading.
2801 * @event resourceloader_loadEnd
2805 var loading
, modules
;
2807 modules
= mw
.loader
.getModuleNames().filter( function ( module
) {
2808 return mw
.loader
.getState( module
) === 'loading';
2810 // We only need a callback, not any actual module. First try a single using()
2811 // for all loading modules. If one fails, fall back to tracking each module
2812 // separately via $.when(), this is expensive.
2813 loading
= mw
.loader
.using( modules
).catch( function () {
2814 var all
= modules
.map( function ( module
) {
2815 return mw
.loader
.using( module
).catch( function () {
2816 return $.Deferred().resolve();
2819 return $.when
.apply( $, all
);
2821 loading
.then( function () {
2822 if ( window
.performance
&& performance
.mark
) {
2823 performance
.mark( 'mwLoadEnd' );
2825 mw
.hook( 'resourceloader.loadEnd' ).fire();
2829 // Attach to window and globally alias
2830 window
.mw
= window
.mediaWiki
= mw
;