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
) {
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 ( Array
.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 ( Array
.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 () {
423 * Write a verbose message to the browser's console in debug mode.
425 * This method is mainly intended for verbose logging. It is a no-op in production mode.
426 * In ResourceLoader debug mode, it will use the browser's console if available, with
427 * fallback to creating a console interface in the DOM and logging messages there.
429 * See {@link mw.log} for other logging methods.
432 * @param {...string} msg Messages to output to console.
434 var log = function () {},
435 console
= window
.console
;
437 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
438 // when adding or removing mw.log methods below!
441 * Collection of methods to help log messages to the console.
448 * Write a message to the browser console's warning channel.
450 * This method is a no-op in browsers that don't implement the Console API.
452 * @param {...string} msg Messages to output to console
454 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
455 Function
.prototype.bind
.call( console
.warn
, console
) :
459 * Write a message to the browser console's error channel.
461 * Most browsers also print a stacktrace when calling this method if the
462 * argument is an Error object.
464 * This method is a no-op in browsers that don't implement the Console API.
467 * @param {Error|...string} msg Messages to output to console
469 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
470 Function
.prototype.bind
.call( console
.error
, console
) :
474 * Create a property on a host object that, when accessed, will produce
475 * a deprecation warning in the console.
477 * @param {Object} obj Host object of deprecated property
478 * @param {string} key Name of property to create in `obj`
479 * @param {Mixed} val The value this property should return when accessed
480 * @param {string} [msg] Optional text to include in the deprecation message
481 * @param {string} [logName=key] Optional custom name for the feature.
482 * This is used instead of `key` in the message and `mw.deprecate` tracking.
484 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
486 } : function ( obj
, key
, val
, msg
, logName
) {
487 var logged
= new StringSet();
488 logName
= logName
|| key
;
489 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
490 function uniqueTrace() {
491 var trace
= new Error().stack
;
492 if ( logged
.has( trace
) ) {
498 // Support: Safari 5.0
499 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
500 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
502 Object
.defineProperty( obj
, key
, {
506 if ( uniqueTrace() ) {
507 mw
.track( 'mw.deprecate', logName
);
512 set: function ( newVal
) {
513 if ( uniqueTrace() ) {
514 mw
.track( 'mw.deprecate', logName
);
527 /* eslint-enable no-console */
533 redefineFallbacksForTest: function () {
534 if ( !window
.QUnit
) {
535 throw new Error( 'Reset not allowed outside unit tests' );
541 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
543 * On browsers that implement the Navigation Timing API, this function will produce floating-point
544 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
545 * it will fall back to using `Date`.
547 * @return {number} Current time
550 // mwNow is defined in startup.js
553 * Format a string. Replace $1, $2 ... $N with positional arguments.
555 * Used by Message#parser().
558 * @param {string} formatString Format string
559 * @param {...Mixed} parameters Values for $N replacements
560 * @return {string} Formatted string
562 format: function ( formatString
) {
563 var parameters
= slice
.call( arguments
, 1 );
564 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
565 var index
= parseInt( match
, 10 ) - 1;
566 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
571 * Track an analytic event.
573 * This method provides a generic means for MediaWiki JavaScript code to capture state
574 * information for analysis. Each logged event specifies a string topic name that describes
575 * the kind of event that it is. Topic names consist of dot-separated path components,
576 * arranged from most general to most specific. Each path component should have a clear and
577 * well-defined purpose.
579 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
580 * events that match their subcription, including those that fired before the handler was
583 * @param {string} topic Topic name
584 * @param {Object} [data] Data describing the event, encoded as an object
586 track: function ( topic
, data
) {
587 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
588 trackCallbacks
.fire( trackQueue
);
592 * Register a handler for subset of analytic events, specified by topic.
594 * Handlers will be called once for each tracked event, including any events that fired before the
595 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
596 * the exact time at which the event fired, a string 'topic' property naming the event, and a
597 * 'data' property which is an object of event-specific data. The event topic and event data are
598 * also passed to the callback as the first and second arguments, respectively.
600 * @param {string} topic Handle events whose name starts with this string prefix
601 * @param {Function} callback Handler to call for each matching tracked event
602 * @param {string} callback.topic
603 * @param {Object} [callback.data]
605 trackSubscribe: function ( topic
, callback
) {
607 function handler( trackQueue
) {
609 for ( ; seen
< trackQueue
.length
; seen
++ ) {
610 event
= trackQueue
[ seen
];
611 if ( event
.topic
.indexOf( topic
) === 0 ) {
612 callback
.call( event
, event
.topic
, event
.data
);
617 trackHandlers
.push( [ handler
, callback
] );
619 trackCallbacks
.add( handler
);
623 * Stop handling events for a particular handler
625 * @param {Function} callback
627 trackUnsubscribe: function ( callback
) {
628 trackHandlers
= trackHandlers
.filter( function ( fns
) {
629 if ( fns
[ 1 ] === callback
) {
630 trackCallbacks
.remove( fns
[ 0 ] );
631 // Ensure the tuple is removed to avoid holding on to closures
638 // Expose Map constructor
641 // Expose Message constructor
645 * Map of configuration values.
647 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
650 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
651 * global `window` object.
653 * @property {mw.Map} config
655 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
659 * Empty object for third-party libraries, for cases where you don't
660 * want to add a new global, or the global is bad and needs containment
668 * Access container for deprecated functionality that can be moved from
669 * from their legacy location and attached to this object (e.g. a global
670 * function that is deprecated and as stop-gap can be exposed through here).
672 * This was reserved for future use but never ended up being used.
674 * @deprecated since 1.22 Let deprecated identifiers keep their original name
675 * and use mw.log#deprecate to create an access container for tracking.
681 * Store for messages.
688 * Store for templates associated with a module.
692 templates
: new Map(),
695 * Get a message object.
697 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
700 * @param {string} key Key of message to get
701 * @param {...Mixed} parameters Values for $N replacements
702 * @return {mw.Message}
704 message: function ( key
) {
705 var parameters
= slice
.call( arguments
, 1 );
706 return new Message( mw
.messages
, key
, parameters
);
710 * Get a message string using the (default) 'text' format.
712 * Shortcut for `mw.message( key, parameters... ).text()`.
715 * @param {string} key Key of message to get
716 * @param {...Mixed} parameters Values for $N replacements
720 return mw
.message
.apply( mw
.message
, arguments
).toString();
727 * Client for ResourceLoader server end point.
729 * This client is in charge of maintaining the module registry and state
730 * machine, initiating network (batch) requests for loading modules, as
731 * well as dependency resolution and execution of source code.
733 * For more information, refer to
734 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
739 loader
: ( function () {
742 * Fired via mw.track on various resource loading errors.
744 * @event resourceloader_exception
745 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
746 * object, but in theory module code could manually throw something else, and that
747 * might also end up here.
748 * @param {string} [module] Name of the module which caused the error. Omitted if the
749 * error is not module-related or the module cannot be easily identified due to
751 * @param {string} source Source of the error. Possible values:
753 * - style: stylesheet error (only affects old IE where a special style loading method
755 * - load-callback: exception thrown by user callback
756 * - module-execute: exception thrown by module code
757 * - resolve: failed to sort dependencies for a module in mw.loader.load
758 * - store-eval: could not evaluate module code cached in localStorage
759 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
760 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
761 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
765 * Fired via mw.track on resource loading error conditions.
767 * @event resourceloader_assert
768 * @param {string} source Source of the error. Possible values:
770 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
771 * bug; see <https://phabricator.wikimedia.org/T59567> for details
775 * Mapping of registered modules.
777 * See #implement and #execute for exact details on support for script, style and messages.
783 * // From mw.loader.register()
784 * 'version': '########' (hash)
785 * 'dependencies': ['required.foo', 'bar.also', ...]
786 * 'group': 'somegroup', (or) null
787 * 'source': 'local', (or) 'anotherwiki'
788 * 'skip': 'return !!window.Example', (or) null
789 * 'module': export Object
791 * // Set from execute() or mw.loader.state()
792 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
794 * // Optionally added at run-time by mw.loader.implement()
796 * 'script': closure, array of urls, or string
797 * 'style': { ... } (see #execute)
798 * 'messages': { 'key': 'value', ... }
805 * The module is known to the system but not yet required.
806 * Meta data is registered via mw.loader#register. Calls to that method are
807 * generated server-side by the startup module.
809 * The module was required through mw.loader (either directly or as dependency of
810 * another module). The client will fetch module contents from the server.
811 * The contents are then stashed in the registry via mw.loader#implement.
813 * The module has been loaded from the server and stashed via mw.loader#implement.
814 * If the module has no more dependencies in-flight, the module will be executed
815 * immediately. Otherwise execution is deferred, controlled via #handlePending.
817 * The module is being executed.
819 * The module has been successfully executed.
821 * The module (or one of its dependencies) produced an error during execution.
823 * The module was registered client-side and requested, but the server denied knowledge
824 * of the module's existence.
830 // Mapping of sources, keyed by source-id, values are strings.
835 // 'sourceId': 'http://example.org/w/load.php'
840 // For queueModuleScript()
841 handlingPendingRequests
= false,
842 pendingRequests
= [],
844 // List of modules to be loaded
848 * List of callback jobs waiting for modules to be ready.
850 * Jobs are created by #enqueue() and run by #handlePending().
852 * Typically when a job is created for a module, the job's dependencies contain
853 * both the required module and all its recursive dependencies.
858 * 'dependencies': [ module names ],
859 * 'ready': Function callback
860 * 'error': Function callback
863 * @property {Object[]} jobs
869 * For #addEmbeddedCSS() and #addLink()
872 * @property {HTMLElement|null} marker
874 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
876 // For addEmbeddedCSS()
878 cssBufferTimer
= null,
880 rAF
= window
.requestAnimationFrame
|| setTimeout
;
883 * Create a new style element and add it to the DOM.
886 * @param {string} text CSS text
887 * @param {Node|null} [nextNode] The element where the style tag
888 * should be inserted before
889 * @return {HTMLElement} Reference to the created style element
891 function newStyleTag( text
, nextNode
) {
892 var el
= document
.createElement( 'style' );
893 el
.appendChild( document
.createTextNode( text
) );
894 if ( nextNode
&& nextNode
.parentNode
) {
895 nextNode
.parentNode
.insertBefore( el
, nextNode
);
897 document
.head
.appendChild( el
);
903 * Add a bit of CSS text to the current browser page.
905 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
906 * or create a new one based on whether the given `cssText` is safe for extension.
909 * @param {string} [cssText=cssBuffer] If called without cssText,
910 * the internal buffer will be inserted instead.
911 * @param {Function} [callback]
913 function addEmbeddedCSS( cssText
, callback
) {
914 function fireCallbacks() {
916 oldCallbacks
= cssCallbacks
;
917 // Reset cssCallbacks variable so it's not polluted by any calls to
918 // addEmbeddedCSS() from one of the callbacks (T105973)
920 for ( i
= 0; i
< oldCallbacks
.length
; i
++ ) {
926 cssCallbacks
.push( callback
);
929 // Yield once before creating the <style> tag. This lets multiple stylesheets
930 // accumulate into one buffer, allowing us to reduce how often new stylesheets
931 // are inserted in the browser. Appending a stylesheet and waiting for the
932 // browser to repaint is fairly expensive. (T47810)
934 // Don't extend the buffer if the item needs its own stylesheet.
935 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
936 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
937 // Linebreak for somewhat distinguishable sections
938 cssBuffer
+= '\n' + cssText
;
939 if ( !cssBufferTimer
) {
940 cssBufferTimer
= rAF( function () {
941 // Wrap in anonymous function that takes no arguments
942 // Support: Firefox < 13
943 // Firefox 12 has non-standard behaviour of passing a number
944 // as first argument to a setTimeout callback.
945 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
952 // This is a scheduled flush for the buffer
954 cssBufferTimer
= null;
959 newStyleTag( cssText
, marker
);
966 * @param {Array} modules List of module names
967 * @return {string} Hash of concatenated version hashes.
969 function getCombinedVersion( modules
) {
970 var hashes
= modules
.map( function ( module
) {
971 return registry
[ module
].version
;
973 return fnv132( hashes
.join( '' ) );
977 * Determine whether all dependencies are in state 'ready', which means we may
978 * execute the module or job now.
981 * @param {Array} modules Names of modules to be checked
982 * @return {boolean} True if all modules are in state 'ready', false otherwise
984 function allReady( modules
) {
986 for ( i
= 0; i
< modules
.length
; i
++ ) {
987 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
995 * Determine whether all dependencies are in state 'ready', which means we may
996 * execute the module or job now.
999 * @param {Array} modules Names of modules to be checked
1000 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1002 function anyFailed( modules
) {
1004 for ( i
= 0; i
< modules
.length
; i
++ ) {
1005 state
= mw
.loader
.getState( modules
[ i
] );
1006 if ( state
=== 'error' || state
=== 'missing' ) {
1014 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1015 * pending jobs and modules that depend upon this module. If the given module failed,
1016 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1017 * all jobs/modules now having their dependencies satisfied.
1019 * Jobs that depend on a failed module, will have their error callback ran (if any).
1022 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1024 function handlePending( module
) {
1025 var j
, job
, hasErrors
, m
, stateChange
;
1027 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1028 // If the current module failed, mark all dependent modules also as failed.
1029 // Iterate until steady-state to propagate the error state upwards in the
1032 stateChange
= false;
1033 for ( m
in registry
) {
1034 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1035 if ( anyFailed( registry
[ m
].dependencies
) ) {
1036 registry
[ m
].state
= 'error';
1041 } while ( stateChange
);
1044 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1045 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1046 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1047 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1048 // All dependencies satisfied, or some have errors
1050 jobs
.splice( j
, 1 );
1054 if ( typeof job
.error
=== 'function' ) {
1055 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1058 if ( typeof job
.ready
=== 'function' ) {
1063 // A user-defined callback raised an exception.
1064 // Swallow it to protect our state machine!
1065 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1070 if ( registry
[ module
].state
=== 'ready' ) {
1071 // The current module became 'ready'. Set it in the module store, and recursively execute all
1072 // dependent modules that are loaded and now have all dependencies satisfied.
1073 mw
.loader
.store
.set( module
, registry
[ module
] );
1074 for ( m
in registry
) {
1075 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1083 * Resolve dependencies and detect circular references.
1086 * @param {string} module Name of the top-level module whose dependencies shall be
1087 * resolved and sorted.
1088 * @param {Array} resolved Returns a topological sort of the given module and its
1089 * dependencies, such that later modules depend on earlier modules. The array
1090 * contains the module names. If the array contains already some module names,
1091 * this function appends its result to the pre-existing array.
1092 * @param {StringSet} [unresolved] Used to track the current dependency
1093 * chain, and to report loops in the dependency graph.
1094 * @throws {Error} If any unregistered module or a dependency loop is encountered
1096 function sortDependencies( module
, resolved
, unresolved
) {
1099 if ( !hasOwn
.call( registry
, module
) ) {
1100 throw new Error( 'Unknown dependency: ' + module
);
1103 if ( registry
[ module
].skip
!== null ) {
1104 // eslint-disable-next-line no-new-func
1105 skip
= new Function( registry
[ module
].skip
);
1106 registry
[ module
].skip
= null;
1108 registry
[ module
].skipped
= true;
1109 registry
[ module
].dependencies
= [];
1110 registry
[ module
].state
= 'ready';
1111 handlePending( module
);
1116 if ( resolved
.indexOf( module
) !== -1 ) {
1117 // Module already resolved; nothing to do
1120 // Create unresolved if not passed in
1121 if ( !unresolved
) {
1122 unresolved
= new StringSet();
1124 // Tracks down dependencies
1125 deps
= registry
[ module
].dependencies
;
1126 for ( i
= 0; i
< deps
.length
; i
++ ) {
1127 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
1128 if ( unresolved
.has( deps
[ i
] ) ) {
1129 throw new Error( mw
.format(
1130 'Circular reference detected: $1 -> $2',
1136 unresolved
.add( module
);
1137 sortDependencies( deps
[ i
], resolved
, unresolved
);
1140 resolved
.push( module
);
1144 * Get names of module that a module depends on, in their proper dependency order.
1147 * @param {string[]} modules Array of string module names
1148 * @return {Array} List of dependencies, including 'module'.
1149 * @throws {Error} If an unregistered module or a dependency loop is encountered
1151 function resolve( modules
) {
1152 var i
, resolved
= [];
1153 for ( i
= 0; i
< modules
.length
; i
++ ) {
1154 sortDependencies( modules
[ i
], resolved
);
1160 * Like #resolve(), except it will silently ignore modules that
1161 * are missing or have missing dependencies.
1164 * @param {string[]} modules Array of string module names
1165 * @return {Array} List of dependencies.
1167 function resolveStubbornly( modules
) {
1168 var i
, saved
, resolved
= [];
1169 for ( i
= 0; i
< modules
.length
; i
++ ) {
1170 saved
= resolved
.slice();
1172 sortDependencies( modules
[ i
], resolved
);
1174 // This module is unknown or has unknown dependencies.
1175 // Undo any incomplete resolutions made and keep going.
1177 mw
.track( 'resourceloader.exception', {
1187 * Load and execute a script.
1190 * @param {string} src URL to script, will be used as the src attribute in the script tag
1191 * @param {Function} [callback] Callback to run after request resolution
1193 function addScript( src
, callback
) {
1194 var promise
= $.ajax( {
1197 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1198 // XHR for a same domain request instead of <script>, which changes the request
1199 // headers (potentially missing a cache hit), and reduces caching in general
1200 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1201 // text, so we'd need to $.globalEval, which then messes up line numbers.
1207 promise
.always( callback
);
1212 * Queue the loading and execution of a script for a particular module.
1215 * @param {string} src URL of the script
1216 * @param {string} moduleName Name of currently executing module
1217 * @param {Function} callback Callback to run after addScript() resolution
1219 function queueModuleScript( src
, moduleName
, callback
) {
1220 pendingRequests
.push( function () {
1221 if ( hasOwn
.call( registry
, moduleName
) ) {
1222 // Emulate runScript() part of execute()
1223 window
.require
= mw
.loader
.require
;
1224 window
.module
= registry
[ moduleName
].module
;
1226 addScript( src
, function () {
1227 // 'module.exports' should not persist after the file is executed to
1228 // avoid leakage to unrelated code. 'require' should be kept, however,
1229 // as asynchronous access to 'require' is allowed and expected. (T144879)
1230 delete window
.module
;
1232 // Start the next one (if any)
1233 if ( pendingRequests
[ 0 ] ) {
1234 pendingRequests
.shift()();
1236 handlingPendingRequests
= false;
1240 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1241 handlingPendingRequests
= true;
1242 pendingRequests
.shift()();
1247 * Utility function for execute()
1250 * @param {string} [media] Media attribute
1251 * @param {string} url URL
1253 function addLink( media
, url
) {
1254 var el
= document
.createElement( 'link' );
1256 el
.rel
= 'stylesheet';
1257 if ( media
&& media
!== 'all' ) {
1260 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1261 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1264 if ( marker
&& marker
.parentNode
) {
1265 marker
.parentNode
.insertBefore( el
, marker
);
1267 document
.head
.appendChild( el
);
1272 * Executes a loaded module, making it ready to use
1275 * @param {string} module Module name to execute
1277 function execute( module
) {
1278 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1279 cssHandlesRegistered
= false;
1281 if ( !hasOwn
.call( registry
, module
) ) {
1282 throw new Error( 'Module has not been registered yet: ' + module
);
1284 if ( registry
[ module
].state
!== 'loaded' ) {
1285 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1288 registry
[ module
].state
= 'executing';
1290 runScript = function () {
1291 var script
, markModuleReady
, nestedAddScript
;
1293 script
= registry
[ module
].script
;
1294 markModuleReady = function () {
1295 registry
[ module
].state
= 'ready';
1296 handlePending( module
);
1298 nestedAddScript = function ( arr
, callback
, i
) {
1299 // Recursively call queueModuleScript() in its own callback
1300 // for each element of arr.
1301 if ( i
>= arr
.length
) {
1302 // We're at the end of the array
1307 queueModuleScript( arr
[ i
], module
, function () {
1308 nestedAddScript( arr
, callback
, i
+ 1 );
1313 if ( Array
.isArray( script
) ) {
1314 nestedAddScript( script
, markModuleReady
, 0 );
1315 } else if ( typeof script
=== 'function' ) {
1316 // Pass jQuery twice so that the signature of the closure which wraps
1317 // the script can bind both '$' and 'jQuery'.
1318 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1321 } else if ( typeof script
=== 'string' ) {
1322 // Site and user modules are legacy scripts that run in the global scope.
1323 // This is transported as a string instead of a function to avoid needing
1324 // to use string manipulation to undo the function wrapper.
1325 $.globalEval( script
);
1329 // Module without script
1333 // Use mw.track instead of mw.log because these errors are common in production mode
1334 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1335 registry
[ module
].state
= 'error';
1336 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1337 handlePending( module
);
1341 // Add localizations to message system
1342 if ( registry
[ module
].messages
) {
1343 mw
.messages
.set( registry
[ module
].messages
);
1346 // Initialise templates
1347 if ( registry
[ module
].templates
) {
1348 mw
.templates
.set( module
, registry
[ module
].templates
);
1351 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1354 checkCssHandles = function () {
1355 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1356 // one of the cssHandles is fired while we're still creating more handles.
1357 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1358 if ( module
=== 'user' ) {
1359 // Implicit dependency on the site module. Not real dependency because
1360 // it should run after 'site' regardless of whether it succeeds or fails.
1361 mw
.loader
.using( [ 'site' ] ).always( runScript
);
1365 runScript
= undefined; // Revoke
1368 cssHandle = function () {
1369 var check
= checkCssHandles
;
1371 return function () {
1375 check
= undefined; // Revoke
1381 // Process styles (see also mw.loader.implement)
1382 // * back-compat: { <media>: css }
1383 // * back-compat: { <media>: [url, ..] }
1384 // * { "css": [css, ..] }
1385 // * { "url": { <media>: [url, ..] } }
1386 if ( registry
[ module
].style
) {
1387 for ( key
in registry
[ module
].style
) {
1388 value
= registry
[ module
].style
[ key
];
1391 if ( key
!== 'url' && key
!== 'css' ) {
1392 // Backwards compatibility, key is a media-type
1393 if ( typeof value
=== 'string' ) {
1394 // back-compat: { <media>: css }
1395 // Ignore 'media' because it isn't supported (nor was it used).
1396 // Strings are pre-wrapped in "@media". The media-type was just ""
1397 // (because it had to be set to something).
1398 // This is one of the reasons why this format is no longer used.
1399 addEmbeddedCSS( value
, cssHandle() );
1401 // back-compat: { <media>: [url, ..] }
1407 // Array of css strings in key 'css',
1408 // or back-compat array of urls from media-type
1409 if ( Array
.isArray( value
) ) {
1410 for ( i
= 0; i
< value
.length
; i
++ ) {
1411 if ( key
=== 'bc-url' ) {
1412 // back-compat: { <media>: [url, ..] }
1413 addLink( media
, value
[ i
] );
1414 } else if ( key
=== 'css' ) {
1415 // { "css": [css, ..] }
1416 addEmbeddedCSS( value
[ i
], cssHandle() );
1419 // Not an array, but a regular object
1420 // Array of urls inside media-type key
1421 } else if ( typeof value
=== 'object' ) {
1422 // { "url": { <media>: [url, ..] } }
1423 for ( media
in value
) {
1424 urls
= value
[ media
];
1425 for ( i
= 0; i
< urls
.length
; i
++ ) {
1426 addLink( media
, urls
[ i
] );
1434 cssHandlesRegistered
= true;
1439 * Add one or more modules to the module load queue.
1444 * @param {string|string[]} dependencies Module name or array of string module names
1445 * @param {Function} [ready] Callback to execute when all dependencies are ready
1446 * @param {Function} [error] Callback to execute when any dependency fails
1448 function enqueue( dependencies
, ready
, error
) {
1449 // Allow calling by single module name
1450 if ( typeof dependencies
=== 'string' ) {
1451 dependencies
= [ dependencies
];
1454 // Add ready and error callbacks if they were given
1455 if ( ready
!== undefined || error
!== undefined ) {
1457 // Narrow down the list to modules that are worth waiting for
1458 dependencies
: dependencies
.filter( function ( module
) {
1459 var state
= mw
.loader
.getState( module
);
1460 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1467 dependencies
.forEach( function ( module
) {
1468 var state
= mw
.loader
.getState( module
);
1469 // Only queue modules that are still in the initial 'registered' state
1470 // (not ones already loading, ready or error).
1471 if ( state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1472 // Private modules must be embedded in the page. Don't bother queuing
1473 // these as the server will deny them anyway (T101806).
1474 if ( registry
[ module
].group
=== 'private' ) {
1475 registry
[ module
].state
= 'error';
1476 handlePending( module
);
1479 queue
.push( module
);
1486 function sortQuery( o
) {
1495 for ( key
= 0; key
< a
.length
; key
++ ) {
1496 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1502 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1503 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1505 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1506 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1508 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1509 * because its implementation needs to keep track of potential string size in order
1510 * to decide when to split the requests due to url size.
1513 * @param {Object} moduleMap Module map
1515 * @return {string} return.str Module query string
1516 * @return {Array} return.list List of module names in matching order
1518 function buildModulesString( moduleMap
) {
1523 function restore( suffix
) {
1527 for ( prefix
in moduleMap
) {
1528 p
= prefix
=== '' ? '' : prefix
+ '.';
1529 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1530 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1533 str
: str
.join( '|' ),
1539 * Resolve indexed dependencies.
1541 * ResourceLoader uses an optimization to save space which replaces module names in
1542 * dependency lists with the index of that module within the array of module
1543 * registration data if it exists. The benefit is a significant reduction in the data
1544 * size of the startup module. This function changes those dependency lists back to
1545 * arrays of strings.
1548 * @param {Array} modules Modules array
1550 function resolveIndexedDependencies( modules
) {
1552 function resolveIndex( dep
) {
1553 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1555 for ( i
= 0; i
< modules
.length
; i
++ ) {
1556 deps
= modules
[ i
][ 2 ];
1558 for ( j
= 0; j
< deps
.length
; j
++ ) {
1559 deps
[ j
] = resolveIndex( deps
[ j
] );
1566 * Create network requests for a batch of modules.
1568 * This is an internal method for #work(). This must not be called directly
1569 * unless the modules are already registered, and no request is in progress,
1570 * and the module state has already been set to `loading`.
1573 * @param {string[]} batch
1575 function batchRequest( batch
) {
1576 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1577 source
, group
, i
, modules
, sourceLoadScript
,
1578 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1579 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1582 * Start the currently drafted request to the server.
1586 function doRequest() {
1587 // Optimisation: Inherit (Object.create), not copy ($.extend)
1588 var query
= Object
.create( currReqBase
),
1589 packed
= buildModulesString( moduleMap
);
1590 query
.modules
= packed
.str
;
1591 // The packing logic can change the effective order, even if the input was
1592 // sorted. As such, the call to getCombinedVersion() must use this
1593 // effective order, instead of currReqModules, as otherwise the combined
1594 // version will not match the hash expected by the server based on
1595 // combining versions from the module query string in-order. (T188076)
1596 query
.version
= getCombinedVersion( packed
.list
);
1597 query
= sortQuery( query
);
1598 addScript( sourceLoadScript
+ '?' + $.param( query
) );
1601 if ( !batch
.length
) {
1605 // Always order modules alphabetically to help reduce cache
1606 // misses for otherwise identical content.
1609 // Query parameters common to all requests
1611 skin
: mw
.config
.get( 'skin' ),
1612 lang
: mw
.config
.get( 'wgUserLanguage' ),
1613 debug
: mw
.config
.get( 'debug' )
1615 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1617 // Split module list by source and by group.
1619 for ( b
= 0; b
< batch
.length
; b
++ ) {
1620 bSource
= registry
[ batch
[ b
] ].source
;
1621 bGroup
= registry
[ batch
[ b
] ].group
;
1622 if ( !hasOwn
.call( splits
, bSource
) ) {
1623 splits
[ bSource
] = {};
1625 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1626 splits
[ bSource
][ bGroup
] = [];
1628 bSourceGroup
= splits
[ bSource
][ bGroup
];
1629 bSourceGroup
.push( batch
[ b
] );
1632 for ( source
in splits
) {
1634 sourceLoadScript
= sources
[ source
];
1636 for ( group
in splits
[ source
] ) {
1638 // Cache access to currently selected list of
1639 // modules for this group from this source.
1640 modules
= splits
[ source
][ group
];
1642 // Query parameters common to requests for this module group
1643 // Optimisation: Inherit (Object.create), not copy ($.extend)
1644 currReqBase
= Object
.create( reqBase
);
1645 // User modules require a user name in the query string.
1646 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1647 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1650 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1651 // > '&modules='.length === 9
1652 // > '&version=1234567'.length === 16
1654 currReqBaseLength
= $.param( currReqBase
).length
+ 25;
1656 // We may need to split up the request to honor the query string length limit,
1657 // so build it piece by piece.
1658 l
= currReqBaseLength
;
1659 moduleMap
= {}; // { prefix: [ suffixes ] }
1660 currReqModules
= [];
1662 for ( i
= 0; i
< modules
.length
; i
++ ) {
1663 // Determine how many bytes this module would add to the query string
1664 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1665 // If lastDotIndex is -1, substr() returns an empty string
1666 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1667 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1668 bytesAdded
= hasOwn
.call( moduleMap
, prefix
) ?
1669 suffix
.length
+ 3 : // '%2C'.length == 3
1670 modules
[ i
].length
+ 3; // '%7C'.length == 3
1672 // If the url would become too long, create a new one, but don't create empty requests
1673 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1674 // Dispatch what we've got...
1676 // .. and start again.
1677 l
= currReqBaseLength
;
1679 currReqModules
= [];
1681 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1683 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1684 moduleMap
[ prefix
] = [];
1687 moduleMap
[ prefix
].push( suffix
);
1688 currReqModules
.push( modules
[ i
] );
1690 // If there's anything left in moduleMap, request that too
1691 if ( currReqModules
.length
) {
1700 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1701 * form of calls to mw.loader#implement().
1702 * @param {Function} cb Callback in case of failure
1703 * @param {Error} cb.err
1705 function asyncEval( implementations
, cb
) {
1706 if ( !implementations
.length
) {
1709 mw
.requestIdleCallback( function () {
1711 $.globalEval( implementations
.join( ';' ) );
1719 * Make a versioned key for a specific module.
1722 * @param {string} module Module name
1723 * @return {string|null} Module key in format '`[name]@[version]`',
1724 * or null if the module does not exist
1726 function getModuleKey( module
) {
1727 return hasOwn
.call( registry
, module
) ?
1728 ( module
+ '@' + registry
[ module
].version
) : null;
1733 * @param {string} key Module name or '`[name]@[version]`'
1736 function splitModuleKey( key
) {
1737 var index
= key
.indexOf( '@' );
1738 if ( index
=== -1 ) {
1745 name
: key
.slice( 0, index
),
1746 version
: key
.slice( index
+ 1 )
1750 /* Public Members */
1753 * The module registry is exposed as an aid for debugging and inspecting page
1754 * state; it is not a public interface for modifying the registry.
1760 moduleRegistry
: registry
,
1763 * @inheritdoc #newStyleTag
1766 addStyleTag
: newStyleTag
,
1769 * Start loading of all queued module dependencies.
1774 var q
, batch
, implementations
, sourceModules
;
1778 // Appends a list of modules from the queue to the batch
1779 for ( q
= 0; q
< queue
.length
; q
++ ) {
1780 // Only load modules which are registered
1781 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1782 // Prevent duplicate entries
1783 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1784 batch
.push( queue
[ q
] );
1785 // Mark registered modules as loading
1786 registry
[ queue
[ q
] ].state
= 'loading';
1791 // Now that the queue has been processed into a batch, clear the queue.
1792 // This MUST happen before we initiate any eval or network request. Otherwise,
1793 // it is possible for a cached script to instantly trigger the same work queue
1794 // again; all before we've cleared it causing each request to include modules
1795 // which are already loaded.
1798 if ( !batch
.length
) {
1802 mw
.loader
.store
.init();
1803 if ( mw
.loader
.store
.enabled
) {
1804 implementations
= [];
1806 batch
= batch
.filter( function ( module
) {
1807 var implementation
= mw
.loader
.store
.get( module
);
1808 if ( implementation
) {
1809 implementations
.push( implementation
);
1810 sourceModules
.push( module
);
1815 asyncEval( implementations
, function ( err
) {
1817 // Not good, the cached mw.loader.implement calls failed! This should
1818 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1819 // Depending on how corrupt the string is, it is likely that some
1820 // modules' implement() succeeded while the ones after the error will
1821 // never run and leave their modules in the 'loading' state forever.
1822 mw
.loader
.store
.stats
.failed
++;
1824 // Since this is an error not caused by an individual module but by
1825 // something that infected the implement call itself, don't take any
1826 // risks and clear everything in this cache.
1827 mw
.loader
.store
.clear();
1829 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1830 // Re-add the failed ones that are still pending back to the batch
1831 failed
= sourceModules
.filter( function ( module
) {
1832 return registry
[ module
].state
=== 'loading';
1834 batchRequest( failed
);
1838 batchRequest( batch
);
1842 * Register a source.
1844 * The #work() method will use this information to split up requests by source.
1846 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1848 * @param {string|Object} id Source ID, or object mapping ids to load urls
1849 * @param {string} loadUrl Url to a load.php end point
1850 * @throws {Error} If source id is already registered
1852 addSource: function ( id
, loadUrl
) {
1854 // Allow multiple additions
1855 if ( typeof id
=== 'object' ) {
1856 for ( source
in id
) {
1857 mw
.loader
.addSource( source
, id
[ source
] );
1862 if ( hasOwn
.call( sources
, id
) ) {
1863 throw new Error( 'source already registered: ' + id
);
1866 sources
[ id
] = loadUrl
;
1870 * Register a module, letting the system know about it and its properties.
1872 * The startup modules contain calls to this method.
1874 * When using multiple module registration by passing an array, dependencies that
1875 * are specified as references to modules within the array will be resolved before
1876 * the modules are registered.
1878 * @param {string|Array} module Module name or array of arrays, each containing
1879 * a list of arguments compatible with this method
1880 * @param {string|number} version Module version hash (falls backs to empty string)
1881 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1882 * @param {string|Array} dependencies One string or array of strings of module
1883 * names on which this module depends.
1884 * @param {string} [group=null] Group which the module is in
1885 * @param {string} [source='local'] Name of the source
1886 * @param {string} [skip=null] Script body of the skip function
1888 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1890 // Allow multiple registration
1891 if ( typeof module
=== 'object' ) {
1892 resolveIndexedDependencies( module
);
1893 for ( i
= 0; i
< module
.length
; i
++ ) {
1894 // module is an array of module names
1895 if ( typeof module
[ i
] === 'string' ) {
1896 mw
.loader
.register( module
[ i
] );
1897 // module is an array of arrays
1898 } else if ( typeof module
[ i
] === 'object' ) {
1899 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1904 if ( hasOwn
.call( registry
, module
) ) {
1905 throw new Error( 'module already registered: ' + module
);
1907 if ( typeof dependencies
=== 'string' ) {
1908 // A single module name
1909 deps
= [ dependencies
];
1910 } else if ( typeof dependencies
=== 'object' ) {
1911 // Array of module names
1912 deps
= dependencies
;
1914 // List the module as registered
1915 registry
[ module
] = {
1916 // Exposed to execute() for mw.loader.implement() closures.
1917 // Import happens via require().
1921 version
: version
!== undefined ? String( version
) : '',
1922 dependencies
: deps
|| [],
1923 group
: typeof group
=== 'string' ? group
: null,
1924 source
: typeof source
=== 'string' ? source
: 'local',
1925 state
: 'registered',
1926 skip
: typeof skip
=== 'string' ? skip
: null
1931 * Implement a module given the components that make up the module.
1933 * When #load() or #using() requests one or more modules, the server
1934 * response contain calls to this function.
1936 * @param {string} module Name of module and current module version. Formatted
1937 * as '`[name]@[version]`". This version should match the requested version
1938 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1939 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1940 * @param {Function|Array|string} [script] Function with module code, list of URLs
1941 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1942 * @param {Object} [style] Should follow one of the following patterns:
1944 * { "css": [css, ..] }
1945 * { "url": { <media>: [url, ..] } }
1947 * And for backwards compatibility (needs to be supported forever due to caching):
1950 * { <media>: [url, ..] }
1952 * The reason css strings are not concatenated anymore is T33676. We now check
1953 * whether it's safe to extend the stylesheet.
1956 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1957 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1959 implement: function ( module
, script
, style
, messages
, templates
) {
1960 var split
= splitModuleKey( module
),
1962 version
= split
.version
;
1963 // Automatically register module
1964 if ( !hasOwn
.call( registry
, name
) ) {
1965 mw
.loader
.register( name
);
1967 // Check for duplicate implementation
1968 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1969 throw new Error( 'module already implemented: ' + name
);
1972 // Without this reset, if there is a version mismatch between the
1973 // requested and received module version, then mw.loader.store would
1974 // cache the response under the requested key. Thus poisoning the cache
1975 // indefinitely with a stale value. (T117587)
1976 registry
[ name
].version
= version
;
1978 // Attach components
1979 registry
[ name
].script
= script
|| null;
1980 registry
[ name
].style
= style
|| null;
1981 registry
[ name
].messages
= messages
|| null;
1982 registry
[ name
].templates
= templates
|| null;
1983 // The module may already have been marked as erroneous
1984 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1985 registry
[ name
].state
= 'loaded';
1986 if ( allReady( registry
[ name
].dependencies
) ) {
1993 * Execute a function as soon as one or more required modules are ready.
1995 * Example of inline dependency on OOjs:
1997 * mw.loader.using( 'oojs', function () {
1998 * OO.compare( [ 1 ], [ 1 ] );
2001 * Example of inline dependency obtained via `require()`:
2003 * mw.loader.using( [ 'mediawiki.util' ], function ( require ) {
2004 * var util = require( 'mediawiki.util' );
2007 * Since MediaWiki 1.23 this also returns a promise.
2009 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
2011 * @param {string|Array} dependencies Module name or array of modules names the
2012 * callback depends on to be ready before executing
2013 * @param {Function} [ready] Callback to execute when all dependencies are ready
2014 * @param {Function} [error] Callback to execute if one or more dependencies failed
2015 * @return {jQuery.Promise} With a `require` function
2017 using: function ( dependencies
, ready
, error
) {
2018 var deferred
= $.Deferred();
2020 // Allow calling with a single dependency as a string
2021 if ( typeof dependencies
=== 'string' ) {
2022 dependencies
= [ dependencies
];
2026 deferred
.done( ready
);
2029 deferred
.fail( error
);
2033 // Resolve entire dependency map
2034 dependencies
= resolve( dependencies
);
2036 return deferred
.reject( e
).promise();
2038 if ( allReady( dependencies
) ) {
2039 // Run ready immediately
2040 deferred
.resolve( mw
.loader
.require
);
2041 } else if ( anyFailed( dependencies
) ) {
2042 // Execute error immediately if any dependencies have errors
2044 new Error( 'One or more dependencies failed to load' ),
2048 // Not all dependencies are ready, add to the load queue
2049 enqueue( dependencies
, function () {
2050 deferred
.resolve( mw
.loader
.require
);
2051 }, deferred
.reject
);
2054 return deferred
.promise();
2058 * Load an external script or one or more modules.
2060 * This method takes a list of unrelated modules. Use cases:
2062 * - A web page will be composed of many different widgets. These widgets independently
2063 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
2064 * have problems, or are no longer known (e.g. cached HTML), the other modules
2065 * should still be loaded.
2066 * - This method is used for preloading, which must not throw. Later code that
2067 * calls #using() will handle the error.
2069 * @param {string|Array} modules Either the name of a module, array of modules,
2070 * or a URL of an external script or style
2071 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2072 * external script or style; acceptable values are "text/css" and
2073 * "text/javascript"; if no type is provided, text/javascript is assumed.
2075 load: function ( modules
, type
) {
2078 // Allow calling with a url or single dependency as a string
2079 if ( typeof modules
=== 'string' ) {
2080 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2081 if ( /^(https?:)?\/?\//.test( modules
) ) {
2082 if ( type
=== 'text/css' ) {
2083 l
= document
.createElement( 'link' );
2084 l
.rel
= 'stylesheet';
2086 document
.head
.appendChild( l
);
2089 if ( type
=== 'text/javascript' || type
=== undefined ) {
2090 addScript( modules
);
2094 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2096 // Called with single module
2097 modules
= [ modules
];
2100 // Filter out top-level modules that are unknown or failed to load before.
2101 filtered
= modules
.filter( function ( module
) {
2102 var state
= mw
.loader
.getState( module
);
2103 return state
!== 'error' && state
!== 'missing';
2105 // Resolve remaining list using the known dependency tree.
2106 // This also filters out modules with unknown dependencies. (T36853)
2107 filtered
= resolveStubbornly( filtered
);
2108 // If all modules are ready, or if any modules have errors, nothing to be done.
2109 if ( allReady( filtered
) || anyFailed( filtered
) ) {
2112 if ( filtered
.length
=== 0 ) {
2115 // Some modules are not yet ready, add to module load queue.
2116 enqueue( filtered
, undefined, undefined );
2120 * Change the state of one or more modules.
2122 * @param {string|Object} module Module name or object of module name/state pairs
2123 * @param {string} state State name
2125 state: function ( module
, state
) {
2128 if ( typeof module
=== 'object' ) {
2129 for ( m
in module
) {
2130 mw
.loader
.state( m
, module
[ m
] );
2134 if ( !hasOwn
.call( registry
, module
) ) {
2135 mw
.loader
.register( module
);
2137 registry
[ module
].state
= state
;
2138 if ( state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
2139 // Make sure pending modules depending on this one get executed if their
2140 // dependencies are now fulfilled!
2141 handlePending( module
);
2146 * Get the version of a module.
2148 * @param {string} module Name of module
2149 * @return {string|null} The version, or null if the module (or its version) is not
2152 getVersion: function ( module
) {
2153 return hasOwn
.call( registry
, module
) ? registry
[ module
].version
: null;
2157 * Get the state of a module.
2159 * @param {string} module Name of module
2160 * @return {string|null} The state, or null if the module (or its state) is not
2163 getState: function ( module
) {
2164 return hasOwn
.call( registry
, module
) ? registry
[ module
].state
: null;
2168 * Get the names of all registered modules.
2172 getModuleNames: function () {
2173 return Object
.keys( registry
);
2177 * Get the exported value of a module.
2179 * This static method is publicly exposed for debugging purposes
2180 * only and must not be used in production code. In production code,
2181 * please use the dynamically provided `require()` function instead.
2183 * In case of lazy-loaded modules via mw.loader#using(), the returned
2184 * Promise provides the function, see #using() for examples.
2188 * @param {string} moduleName Module name
2189 * @return {Mixed} Exported value
2191 require: function ( moduleName
) {
2192 var state
= mw
.loader
.getState( moduleName
);
2194 // Only ready modules can be required
2195 if ( state
!== 'ready' ) {
2196 // Module may've forgotten to declare a dependency
2197 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2200 return registry
[ moduleName
].module
.exports
;
2204 * @inheritdoc mw.inspect#runReports
2207 inspect: function () {
2208 var args
= slice
.call( arguments
);
2209 mw
.loader
.using( 'mediawiki.inspect', function () {
2210 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2215 * On browsers that implement the localStorage API, the module store serves as a
2216 * smart complement to the browser cache. Unlike the browser cache, the module store
2217 * can slice a concatenated response from ResourceLoader into its constituent
2218 * modules and cache each of them separately, using each module's versioning scheme
2219 * to determine when the cache should be invalidated.
2222 * @class mw.loader.store
2225 // Whether the store is in use on this page.
2228 // Modules whose string representation exceeds 100 kB are
2229 // ineligible for storage. See bug T66721.
2230 MODULE_SIZE_MAX
: 100 * 1000,
2232 // The contents of the store, mapping '[name]@[version]' keys
2233 // to module implementations.
2237 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2240 * Construct a JSON-serializable object representing the content of the store.
2242 * @return {Object} Module store contents.
2244 toJSON: function () {
2245 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2249 * Get the localStorage key for the entire module store. The key references
2250 * $wgDBname to prevent clashes between wikis which share a common host.
2252 * @return {string} localStorage item key
2254 getStoreKey: function () {
2255 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2259 * Get a key on which to vary the module cache.
2261 * @return {string} String of concatenated vary conditions.
2263 getVary: function () {
2265 mw
.config
.get( 'skin' ),
2266 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2267 mw
.config
.get( 'wgUserLanguage' )
2272 * Initialize the store.
2274 * Retrieves store from localStorage and (if successfully retrieved) decoding
2275 * the stored JSON value to a plain object.
2277 * The try / catch block is used for JSON & localStorage feature detection.
2278 * See the in-line documentation for Modernizr's localStorage feature detection
2279 * code for a full account of why we need a try / catch:
2280 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2285 if ( mw
.loader
.store
.enabled
!== null ) {
2291 // Disabled because localStorage quotas are tight and (in Firefox's case)
2292 // shared by multiple origins.
2293 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2294 /Firefox|Opera/.test( navigator
.userAgent
) ||
2296 // Disabled by configuration.
2297 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2299 // Clear any previous store to free up space. (T66721)
2300 mw
.loader
.store
.clear();
2301 mw
.loader
.store
.enabled
= false;
2304 if ( mw
.config
.get( 'debug' ) ) {
2305 // Disable module store in debug mode
2306 mw
.loader
.store
.enabled
= false;
2311 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2312 // If we get here, localStorage is available; mark enabled
2313 mw
.loader
.store
.enabled
= true;
2314 data
= JSON
.parse( raw
);
2315 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2316 mw
.loader
.store
.items
= data
.items
;
2320 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2323 if ( raw
=== undefined ) {
2324 // localStorage failed; disable store
2325 mw
.loader
.store
.enabled
= false;
2327 mw
.loader
.store
.update();
2332 * Retrieve a module from the store and update cache hit stats.
2334 * @param {string} module Module name
2335 * @return {string|boolean} Module implementation or false if unavailable
2337 get: function ( module
) {
2340 if ( !mw
.loader
.store
.enabled
) {
2344 key
= getModuleKey( module
);
2345 if ( key
in mw
.loader
.store
.items
) {
2346 mw
.loader
.store
.stats
.hits
++;
2347 return mw
.loader
.store
.items
[ key
];
2349 mw
.loader
.store
.stats
.misses
++;
2354 * Stringify a module and queue it for storage.
2356 * @param {string} module Module name
2357 * @param {Object} descriptor The module's descriptor as set in the registry
2358 * @return {boolean} Module was set
2360 set: function ( module
, descriptor
) {
2363 if ( !mw
.loader
.store
.enabled
) {
2367 key
= getModuleKey( module
);
2370 // Already stored a copy of this exact version
2371 key
in mw
.loader
.store
.items
||
2372 // Module failed to load
2373 descriptor
.state
!== 'ready' ||
2374 // Unversioned, private, or site-/user-specific
2375 !descriptor
.version
||
2376 descriptor
.group
=== 'private' ||
2377 descriptor
.group
=== 'user' ||
2378 // Partial descriptor
2379 // (e.g. skipped module, or style module with state=ready)
2380 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2381 descriptor
.templates
].indexOf( undefined ) !== -1
2389 JSON
.stringify( key
),
2390 typeof descriptor
.script
=== 'function' ?
2391 String( descriptor
.script
) :
2392 JSON
.stringify( descriptor
.script
),
2393 JSON
.stringify( descriptor
.style
),
2394 JSON
.stringify( descriptor
.messages
),
2395 JSON
.stringify( descriptor
.templates
)
2397 // Attempted workaround for a possible Opera bug (bug T59567).
2398 // This regex should never match under sane conditions.
2399 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2400 args
[ 1 ] = 'function' + args
[ 1 ];
2401 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2404 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2408 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2409 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2412 mw
.loader
.store
.items
[ key
] = src
;
2413 mw
.loader
.store
.update();
2418 * Iterate through the module store, removing any item that does not correspond
2419 * (in name and version) to an item in the module registry.
2421 * @return {boolean} Store was pruned
2423 prune: function () {
2426 if ( !mw
.loader
.store
.enabled
) {
2430 for ( key
in mw
.loader
.store
.items
) {
2431 module
= key
.slice( 0, key
.indexOf( '@' ) );
2432 if ( getModuleKey( module
) !== key
) {
2433 mw
.loader
.store
.stats
.expired
++;
2434 delete mw
.loader
.store
.items
[ key
];
2435 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2436 // This value predates the enforcement of a size limit on cached modules.
2437 delete mw
.loader
.store
.items
[ key
];
2444 * Clear the entire module store right now.
2446 clear: function () {
2447 mw
.loader
.store
.items
= {};
2449 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2450 } catch ( ignored
) {}
2454 * Sync in-memory store back to localStorage.
2456 * This function debounces updates. When called with a flush already pending,
2457 * the call is coalesced into the pending update. The call to
2458 * localStorage.setItem will be naturally deferred until the page is quiescent.
2460 * Because localStorage is shared by all pages from the same origin, if multiple
2461 * pages are loaded with different module sets, the possibility exists that
2462 * modules saved by one page will be clobbered by another. But the impact would
2463 * be minor and the problem would be corrected by subsequent page views.
2467 update
: ( function () {
2468 var hasPendingWrite
= false;
2470 function flushWrites() {
2472 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2476 mw
.loader
.store
.prune();
2477 key
= mw
.loader
.store
.getStoreKey();
2479 // Replacing the content of the module store might fail if the new
2480 // contents would exceed the browser's localStorage size limit. To
2481 // avoid clogging the browser with stale data, always remove the old
2482 // value before attempting to set the new one.
2483 localStorage
.removeItem( key
);
2484 data
= JSON
.stringify( mw
.loader
.store
);
2485 localStorage
.setItem( key
, data
);
2487 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2490 hasPendingWrite
= false;
2493 return function () {
2494 if ( !hasPendingWrite
) {
2495 hasPendingWrite
= true;
2496 mw
.requestIdleCallback( flushWrites
);
2505 * HTML construction helper functions
2512 * output = Html.element( 'div', {}, new Html.Raw(
2513 * Html.element( 'img', { src: '<' } )
2515 * mw.log( output ); // <div><img src="<"/></div>
2520 html
: ( function () {
2521 function escapeCallback( s
) {
2538 * Escape a string for HTML.
2540 * Converts special characters to HTML entities.
2542 * mw.html.escape( '< > \' & "' );
2543 * // Returns < > ' & "
2545 * @param {string} s The string to escape
2546 * @return {string} HTML
2548 escape: function ( s
) {
2549 return s
.replace( /['"<>&]/g, escapeCallback
);
2553 * Create an HTML element string, with safe escaping.
2555 * @param {string} name The tag name.
2556 * @param {Object} [attrs] An object with members mapping element names to values
2557 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2559 * - string: Text to be escaped.
2560 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2561 * - this.Raw: The raw value is directly included.
2562 * - this.Cdata: The raw value is directly included. An exception is
2563 * thrown if it contains any illegal ETAGO delimiter.
2564 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2565 * @return {string} HTML
2567 element: function ( name
, attrs
, contents
) {
2568 var v
, attrName
, s
= '<' + name
;
2571 for ( attrName
in attrs
) {
2572 v
= attrs
[ attrName
];
2573 // Convert name=true, to name=name
2577 } else if ( v
=== false ) {
2580 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2583 if ( contents
=== undefined || contents
=== null ) {
2590 switch ( typeof contents
) {
2593 s
+= this.escape( contents
);
2597 // Convert to string
2598 s
+= String( contents
);
2601 if ( contents
instanceof this.Raw
) {
2602 // Raw HTML inclusion
2603 s
+= contents
.value
;
2604 } else if ( contents
instanceof this.Cdata
) {
2606 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2607 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2609 s
+= contents
.value
;
2611 throw new Error( 'mw.html.element: Invalid type of contents' );
2614 s
+= '</' + name
+ '>';
2619 * Wrapper object for raw HTML passed to mw.html.element().
2621 * @class mw.html.Raw
2623 * @param {string} value
2625 Raw: function ( value
) {
2630 * Wrapper object for CDATA element contents passed to mw.html.element()
2632 * @class mw.html.Cdata
2634 * @param {string} value
2636 Cdata: function ( value
) {
2642 // Skeleton user object, extended by the 'mediawiki.user' module.
2649 * @property {mw.Map}
2653 * @property {mw.Map}
2658 // OOUI widgets specific to MediaWiki
2662 * Registry and firing of events.
2664 * MediaWiki has various interface components that are extended, enhanced
2665 * or manipulated in some other way by extensions, gadgets and even
2668 * This framework helps streamlining the timing of when these other
2669 * code paths fire their plugins (instead of using document-ready,
2670 * which can and should be limited to firing only once).
2672 * Features like navigating to other wiki pages, previewing an edit
2673 * and editing itself – without a refresh – can then retrigger these
2674 * hooks accordingly to ensure everything still works as expected.
2678 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2679 * mw.hook( 'wikipage.content' ).fire( $content );
2681 * Handlers can be added and fired for arbitrary event names at any time. The same
2682 * event can be fired multiple times. The last run of an event is memorized
2683 * (similar to `$(document).ready` and `$.Deferred().done`).
2684 * This means if an event is fired, and a handler added afterwards, the added
2685 * function will be fired right away with the last given event data.
2687 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2688 * Thus allowing flexible use and optimal maintainability and authority control.
2689 * You can pass around the `add` and/or `fire` method to another piece of code
2690 * without it having to know the event name (or `mw.hook` for that matter).
2692 * var h = mw.hook( 'bar.ready' );
2693 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2695 * Note: Events are documented with an underscore instead of a dot in the event
2696 * name due to jsduck not supporting dots in that position.
2700 hook
: ( function () {
2704 * Create an instance of mw.hook.
2708 * @param {string} name Name of hook.
2711 return function ( name
) {
2712 var list
= hasOwn
.call( lists
, name
) ?
2714 lists
[ name
] = $.Callbacks( 'memory' );
2718 * Register a hook handler
2720 * @param {...Function} handler Function to bind.
2726 * Unregister a hook handler
2728 * @param {...Function} handler Function to unbind.
2731 remove
: list
.remove
,
2733 // eslint-disable-next-line valid-jsdoc
2737 * @param {...Mixed} data
2741 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2748 // Alias $j to jQuery for backwards compatibility
2749 // @deprecated since 1.23 Use $ or jQuery instead
2750 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2753 * Log a message to window.console, if possible.
2755 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2756 * also in production mode). Gets console references in each invocation instead of caching the
2757 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2760 * @param {string} topic Stream name passed by mw.track
2761 * @param {Object} data Data passed by mw.track
2762 * @param {Error} [data.exception]
2763 * @param {string} data.source Error source
2764 * @param {string} [data.module] Name of module which caused the error
2766 function logError( topic
, data
) {
2767 /* eslint-disable no-console */
2770 source
= data
.source
,
2771 module
= data
.module
,
2772 console
= window
.console
;
2774 if ( console
&& console
.log
) {
2775 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2777 msg
+= ' in module ' + module
;
2779 msg
+= ( e
? ':' : '.' );
2782 // If we have an exception object, log it to the warning channel to trigger
2783 // proper stacktraces in browsers that support it.
2784 if ( e
&& console
.warn
) {
2788 /* eslint-enable no-console */
2791 // Subscribe to error streams
2792 mw
.trackSubscribe( 'resourceloader.exception', logError
);
2793 mw
.trackSubscribe( 'resourceloader.assert', logError
);
2796 * Fired when all modules associated with the page have finished loading.
2798 * @event resourceloader_loadEnd
2802 var loading
, modules
;
2804 modules
= mw
.loader
.getModuleNames().filter( function ( module
) {
2805 return mw
.loader
.getState( module
) === 'loading';
2807 // We only need a callback, not any actual module. First try a single using()
2808 // for all loading modules. If one fails, fall back to tracking each module
2809 // separately via $.when(), this is expensive.
2810 loading
= mw
.loader
.using( modules
).catch( function () {
2811 var all
= modules
.map( function ( module
) {
2812 return mw
.loader
.using( module
).catch( function () {
2813 return $.Deferred().resolve();
2816 return $.when
.apply( $, all
);
2818 loading
.then( function () {
2819 if ( window
.performance
&& performance
.mark
) {
2820 performance
.mark( 'mwLoadEnd' );
2822 mw
.hook( 'resourceloader.loadEnd' ).fire();
2826 // Attach to window and globally alias
2827 window
.mw
= window
.mediaWiki
= mw
;