2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
11 /* eslint-disable no-use-before-define */
16 var mw
, StringSet
, log
,
17 hasOwn
= Object
.prototype.hasOwnProperty
,
18 slice
= Array
.prototype.slice
,
19 trackCallbacks
= $.Callbacks( 'memory' ),
24 * FNV132 hash function
26 * This function implements the 32-bit version of FNV-1.
27 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
28 * its output is base 36 rather than hex.
29 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
32 * @param {string} str String to hash
33 * @return {string} hash as an seven-character base 36 string
35 function fnv132( str
) {
36 /* eslint-disable no-bitwise */
37 var hash
= 0x811C9DC5,
40 for ( i
= 0; i
< str
.length
; i
++ ) {
41 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
42 hash
^= str
.charCodeAt( i
);
45 hash
= ( hash
>>> 0 ).toString( 36 );
46 while ( hash
.length
< 7 ) {
51 /* eslint-enable no-bitwise */
54 StringSet
= window
.Set
|| ( function () {
59 function StringSet() {
62 StringSet
.prototype.add = function ( value
) {
63 this.set[ value
] = true;
65 StringSet
.prototype.has = function ( value
) {
66 return this.set.hasOwnProperty( value
);
72 * Create an object that can be read from or written to via methods that allow
73 * interaction both with single and multiple properties at once.
79 * @param {boolean} [global=false] Whether to synchronise =values to the global
80 * window object (for backwards-compatibility with mw.config; T72470). Values are
81 * copied in one direction only. Changes to globals do not reflect in the map.
83 function Map( global
) {
84 this.internalValues
= {};
85 if ( global
=== true ) {
87 // Override #set to also set the global variable
88 this.set = function ( selection
, value
) {
91 if ( $.isPlainObject( selection
) ) {
92 for ( s
in selection
) {
93 setGlobalMapValue( this, s
, selection
[ s
] );
97 if ( typeof selection
=== 'string' && arguments
.length
) {
98 setGlobalMapValue( this, selection
, value
);
105 // Deprecated since MediaWiki 1.28
110 'mw.Map#values is deprecated. Use mw.Map#get() instead.',
116 * Alias property to the global object.
120 * @param {mw.Map} map
121 * @param {string} key
122 * @param {Mixed} value
124 function setGlobalMapValue( map
, key
, value
) {
125 map
.internalValues
[ key
] = value
;
130 // Deprecation notice for mw.config globals (T58550, T72470)
131 map
=== mw
.config
&& 'Use mw.config instead.'
139 * Get the value of one or more keys.
141 * If called with no arguments, all values are returned.
143 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
144 * @param {Mixed} [fallback=null] Value for keys that don't exist.
145 * @return {Mixed|Object| null} If selection was a string, returns the value,
146 * If selection was an array, returns an object of key/values.
147 * If no selection is passed, the internal container is returned. (Beware that,
148 * as is the default in JavaScript, the object is returned by reference.)
150 get: function ( selection
, fallback
) {
152 // If we only do this in the `return` block, it'll fail for the
153 // call to get() from the mutli-selection block.
154 fallback
= arguments
.length
> 1 ? fallback
: null;
156 if ( $.isArray( selection
) ) {
157 selection
= slice
.call( selection
);
159 for ( i
= 0; i
< selection
.length
; i
++ ) {
160 results
[ selection
[ i
] ] = this.get( selection
[ i
], fallback
);
165 if ( typeof selection
=== 'string' ) {
166 if ( !hasOwn
.call( this.internalValues
, selection
) ) {
169 return this.internalValues
[ selection
];
172 if ( selection
=== undefined ) {
173 return this.internalValues
;
176 // Invalid selection key
181 * Set one or more key/value pairs.
183 * @param {string|Object} selection Key to set value for, or object mapping keys to values
184 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
185 * @return {boolean} True on success, false on failure
187 set: function ( selection
, value
) {
190 if ( $.isPlainObject( selection
) ) {
191 for ( s
in selection
) {
192 this.internalValues
[ s
] = selection
[ s
];
196 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
197 this.internalValues
[ selection
] = value
;
204 * Check if one or more keys exist.
206 * @param {Mixed} selection Key or array of keys to check
207 * @return {boolean} True if the key(s) exist
209 exists: function ( selection
) {
212 if ( $.isArray( selection
) ) {
213 for ( s
= 0; s
< selection
.length
; s
++ ) {
214 if ( typeof selection
[ s
] !== 'string' || !hasOwn
.call( this.internalValues
, selection
[ s
] ) ) {
220 return typeof selection
=== 'string' && hasOwn
.call( this.internalValues
, selection
);
225 * Object constructor for messages.
227 * Similar to the Message class in MediaWiki PHP.
229 * Format defaults to 'text'.
235 * 'hello': 'Hello world',
236 * 'hello-user': 'Hello, $1!',
237 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
240 * obj = new mw.Message( mw.messages, 'hello' );
241 * mw.log( obj.text() );
244 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
245 * mw.log( obj.text() );
246 * // Hello, John Doe!
248 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
249 * mw.log( obj.text() );
250 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
252 * // Using mw.message shortcut
253 * obj = mw.message( 'hello-user', 'John Doe' );
254 * mw.log( obj.text() );
255 * // Hello, John Doe!
257 * // Using mw.msg shortcut
258 * str = mw.msg( 'hello-user', 'John Doe' );
260 * // Hello, John Doe!
262 * // Different formats
263 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
265 * obj.format = 'text';
266 * str = obj.toString();
271 * // Hello, John "Wiki" <3 Doe!
273 * mw.log( obj.escaped() );
274 * // Hello, John "Wiki" <3 Doe!
279 * @param {mw.Map} map Message store
280 * @param {string} key
281 * @param {Array} [parameters]
283 function Message( map
, key
, parameters
) {
284 this.format
= 'text';
287 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
291 Message
.prototype = {
293 * Get parsed contents of the message.
295 * The default parser does simple $N replacements and nothing else.
296 * This may be overridden to provide a more complex message parser.
297 * The primary override is in the mediawiki.jqueryMsg module.
299 * This function will not be called for nonexistent messages.
301 * @return {string} Parsed message
303 parser: function () {
304 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
308 * Add (does not replace) parameters for `$N` placeholder values.
310 * @param {Array} parameters
313 params: function ( parameters
) {
315 for ( i
= 0; i
< parameters
.length
; i
++ ) {
316 this.parameters
.push( parameters
[ i
] );
322 * Convert message object to its string form based on current format.
324 * @return {string} Message as a string in the current form, or `<key>` if key
327 toString: function () {
330 if ( !this.exists() ) {
331 // Use ⧼key⧽ as text if key does not exist
332 // Err on the side of safety, ensure that the output
333 // is always html safe in the event the message key is
334 // missing, since in that case its highly likely the
335 // message key is user-controlled.
336 // '⧼' is used instead of '<' to side-step any
337 // double-escaping issues.
338 // (Keep synchronised with Message::toString() in PHP.)
339 return '⧼' + mw
.html
.escape( this.key
) + '⧽';
342 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
343 text
= this.parser();
346 if ( this.format
=== 'escaped' ) {
347 text
= this.parser();
348 text
= mw
.html
.escape( text
);
355 * Change format to 'parse' and convert message to string
357 * If jqueryMsg is loaded, this parses the message text from wikitext
358 * (where supported) to HTML
360 * Otherwise, it is equivalent to plain.
362 * @return {string} String form of parsed message
365 this.format
= 'parse';
366 return this.toString();
370 * Change format to 'plain' and convert message to string
372 * This substitutes parameters, but otherwise does not change the
375 * @return {string} String form of plain message
378 this.format
= 'plain';
379 return this.toString();
383 * Change format to 'text' and convert message to string
385 * If jqueryMsg is loaded, {{-transformation is done where supported
386 * (such as {{plural:}}, {{gender:}}, {{int:}}).
388 * Otherwise, it is equivalent to plain
390 * @return {string} String form of text message
393 this.format
= 'text';
394 return this.toString();
398 * Change the format to 'escaped' and convert message to string
400 * This is equivalent to using the 'text' format (see #text), then
401 * HTML-escaping the output.
403 * @return {string} String form of html escaped message
405 escaped: function () {
406 this.format
= 'escaped';
407 return this.toString();
411 * Check if a message exists
416 exists: function () {
417 return this.map
.exists( this.key
);
421 log
= ( function () {
422 // Also update the restoration of methods in mediawiki.log.js
423 // when adding or removing methods here.
424 var log = function () {},
425 console
= window
.console
;
433 * Write a message to the console's warning channel.
434 * Actions not supported by the browser console are silently ignored.
436 * @param {...string} msg Messages to output to console
438 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
439 Function
.prototype.bind
.call( console
.warn
, console
) :
443 * Write a message to the console's error channel.
445 * Most browsers provide a stacktrace by default if the argument
446 * is a caught Error object.
449 * @param {Error|...string} msg Messages to output to console
451 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
452 Function
.prototype.bind
.call( console
.error
, console
) :
456 * Create a property in a host object that, when accessed, will produce
457 * a deprecation warning in the console.
459 * @param {Object} obj Host object of deprecated property
460 * @param {string} key Name of property to create in `obj`
461 * @param {Mixed} val The value this property should return when accessed
462 * @param {string} [msg] Optional text to include in the deprecation message
463 * @param {string} [logName=key] Optional custom name for the feature.
464 * This is used instead of `key` in the message and `mw.deprecate` tracking.
466 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
468 } : function ( obj
, key
, val
, msg
, logName
) {
469 var logged
= new StringSet();
470 logName
= logName
|| key
;
471 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
472 function uniqueTrace() {
473 var trace
= new Error().stack
;
474 if ( logged
.has( trace
) ) {
480 // Support: Safari 5.0
481 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
482 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
484 Object
.defineProperty( obj
, key
, {
488 if ( uniqueTrace() ) {
489 mw
.track( 'mw.deprecate', logName
);
494 set: function ( newVal
) {
495 if ( uniqueTrace() ) {
496 mw
.track( 'mw.deprecate', logName
);
516 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
518 * On browsers that implement the Navigation Timing API, this function will produce floating-point
519 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
520 * it will fall back to using `Date`.
522 * @return {number} Current time
525 var perf
= window
.performance
,
526 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
527 return navStart
&& typeof perf
.now
=== 'function' ?
528 function () { return navStart
+ perf
.now(); } :
529 function () { return +new Date(); };
533 * Format a string. Replace $1, $2 ... $N with positional arguments.
535 * Used by Message#parser().
538 * @param {string} formatString Format string
539 * @param {...Mixed} parameters Values for $N replacements
540 * @return {string} Formatted string
542 format: function ( formatString
) {
543 var parameters
= slice
.call( arguments
, 1 );
544 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
545 var index
= parseInt( match
, 10 ) - 1;
546 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
551 * Track an analytic event.
553 * This method provides a generic means for MediaWiki JavaScript code to capture state
554 * information for analysis. Each logged event specifies a string topic name that describes
555 * the kind of event that it is. Topic names consist of dot-separated path components,
556 * arranged from most general to most specific. Each path component should have a clear and
557 * well-defined purpose.
559 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
560 * events that match their subcription, including those that fired before the handler was
563 * @param {string} topic Topic name
564 * @param {Object} [data] Data describing the event, encoded as an object
566 track: function ( topic
, data
) {
567 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
568 trackCallbacks
.fire( trackQueue
);
572 * Register a handler for subset of analytic events, specified by topic.
574 * Handlers will be called once for each tracked event, including any events that fired before the
575 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
576 * the exact time at which the event fired, a string 'topic' property naming the event, and a
577 * 'data' property which is an object of event-specific data. The event topic and event data are
578 * also passed to the callback as the first and second arguments, respectively.
580 * @param {string} topic Handle events whose name starts with this string prefix
581 * @param {Function} callback Handler to call for each matching tracked event
582 * @param {string} callback.topic
583 * @param {Object} [callback.data]
585 trackSubscribe: function ( topic
, callback
) {
587 function handler( trackQueue
) {
589 for ( ; seen
< trackQueue
.length
; seen
++ ) {
590 event
= trackQueue
[ seen
];
591 if ( event
.topic
.indexOf( topic
) === 0 ) {
592 callback
.call( event
, event
.topic
, event
.data
);
597 trackHandlers
.push( [ handler
, callback
] );
599 trackCallbacks
.add( handler
);
603 * Stop handling events for a particular handler
605 * @param {Function} callback
607 trackUnsubscribe: function ( callback
) {
608 trackHandlers
= $.grep( trackHandlers
, function ( fns
) {
609 if ( fns
[ 1 ] === callback
) {
610 trackCallbacks
.remove( fns
[ 0 ] );
611 // Ensure the tuple is removed to avoid holding on to closures
618 // Expose Map constructor
621 // Expose Message constructor
625 * Map of configuration values.
627 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
630 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
631 * global `window` object.
633 * @property {mw.Map} config
635 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
639 * Empty object for third-party libraries, for cases where you don't
640 * want to add a new global, or the global is bad and needs containment
648 * Access container for deprecated functionality that can be moved from
649 * from their legacy location and attached to this object (e.g. a global
650 * function that is deprecated and as stop-gap can be exposed through here).
652 * This was reserved for future use but never ended up being used.
654 * @deprecated since 1.22 Let deprecated identifiers keep their original name
655 * and use mw.log#deprecate to create an access container for tracking.
661 * Store for messages.
668 * Store for templates associated with a module.
672 templates
: new Map(),
675 * Get a message object.
677 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
680 * @param {string} key Key of message to get
681 * @param {...Mixed} parameters Values for $N replacements
682 * @return {mw.Message}
684 message: function ( key
) {
685 var parameters
= slice
.call( arguments
, 1 );
686 return new Message( mw
.messages
, key
, parameters
);
690 * Get a message string using the (default) 'text' format.
692 * Shortcut for `mw.message( key, parameters... ).text()`.
695 * @param {string} key Key of message to get
696 * @param {...Mixed} parameters Values for $N replacements
700 return mw
.message
.apply( mw
.message
, arguments
).toString();
704 * No-op dummy placeholder for {@link mw.log} in debug mode.
711 * Client for ResourceLoader server end point.
713 * This client is in charge of maintaining the module registry and state
714 * machine, initiating network (batch) requests for loading modules, as
715 * well as dependency resolution and execution of source code.
717 * For more information, refer to
718 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
723 loader
: ( function () {
726 * Fired via mw.track on various resource loading errors.
728 * @event resourceloader_exception
729 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
730 * object, but in theory module code could manually throw something else, and that
731 * might also end up here.
732 * @param {string} [module] Name of the module which caused the error. Omitted if the
733 * error is not module-related or the module cannot be easily identified due to
735 * @param {string} source Source of the error. Possible values:
737 * - style: stylesheet error (only affects old IE where a special style loading method
739 * - load-callback: exception thrown by user callback
740 * - module-execute: exception thrown by module code
741 * - store-eval: could not evaluate module code cached in localStorage
742 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
743 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
744 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
748 * Fired via mw.track on resource loading error conditions.
750 * @event resourceloader_assert
751 * @param {string} source Source of the error. Possible values:
753 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
754 * bug; see <https://phabricator.wikimedia.org/T59567> for details
758 * Mapping of registered modules.
760 * See #implement and #execute for exact details on support for script, style and messages.
766 * // From mw.loader.register()
767 * 'version': '########' (hash)
768 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
769 * 'group': 'somegroup', (or) null
770 * 'source': 'local', (or) 'anotherwiki'
771 * 'skip': 'return !!window.Example', (or) null
772 * 'module': export Object
774 * // Set from execute() or mw.loader.state()
775 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
777 * // Optionally added at run-time by mw.loader.implement()
779 * 'script': closure, array of urls, or string
780 * 'style': { ... } (see #execute)
781 * 'messages': { 'key': 'value', ... }
788 * The module is known to the system but not yet required.
789 * Meta data is registered via mw.loader#register. Calls to that method are
790 * generated server-side by the startup module.
792 * The module was required through mw.loader (either directly or as dependency of
793 * another module). The client will fetch module contents from the server.
794 * The contents are then stashed in the registry via mw.loader#implement.
796 * The module has been loaded from the server and stashed via mw.loader#implement.
797 * If the module has no more dependencies in-flight, the module will be executed
798 * immediately. Otherwise execution is deferred, controlled via #handlePending.
800 * The module is being executed.
802 * The module has been successfully executed.
804 * The module (or one of its dependencies) produced an error during execution.
806 * The module was registered client-side and requested, but the server denied knowledge
807 * of the module's existence.
813 // Mapping of sources, keyed by source-id, values are strings.
818 // 'sourceId': 'http://example.org/w/load.php'
823 // For queueModuleScript()
824 handlingPendingRequests
= false,
825 pendingRequests
= [],
827 // List of modules to be loaded
831 * List of callback jobs waiting for modules to be ready.
833 * Jobs are created by #enqueue() and run by #handlePending().
835 * Typically when a job is created for a module, the job's dependencies contain
836 * both the required module and all its recursive dependencies.
841 * 'dependencies': [ module names ],
842 * 'ready': Function callback
843 * 'error': Function callback
846 * @property {Object[]} jobs
854 // For addEmbeddedCSS()
856 cssBufferTimer
= null,
857 cssCallbacks
= $.Callbacks(),
858 isIE9
= document
.documentMode
=== 9,
859 rAF
= window
.requestAnimationFrame
|| setTimeout
;
861 function getMarker() {
864 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
866 mw
.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
867 marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
874 * Create a new style element and add it to the DOM.
877 * @param {string} text CSS text
878 * @param {Node} [nextNode] The element where the style tag
879 * should be inserted before
880 * @return {HTMLElement} Reference to the created style element
882 function newStyleTag( text
, nextNode
) {
883 var s
= document
.createElement( 'style' );
885 s
.appendChild( document
.createTextNode( text
) );
886 if ( nextNode
&& nextNode
.parentNode
) {
887 nextNode
.parentNode
.insertBefore( s
, nextNode
);
889 document
.getElementsByTagName( 'head' )[ 0 ].appendChild( s
);
896 * Add a bit of CSS text to the current browser page.
898 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
899 * or create a new one based on whether the given `cssText` is safe for extension.
902 * @param {string} [cssText=cssBuffer] If called without cssText,
903 * the internal buffer will be inserted instead.
904 * @param {Function} [callback]
906 function addEmbeddedCSS( cssText
, callback
) {
909 function fireCallbacks() {
910 var oldCallbacks
= cssCallbacks
;
911 // Reset cssCallbacks variable so it's not polluted by any calls to
912 // addEmbeddedCSS() from one of the callbacks (T105973)
913 cssCallbacks
= $.Callbacks();
914 oldCallbacks
.fire().empty();
918 cssCallbacks
.add( callback
);
921 // Yield once before creating the <style> tag. This lets multiple stylesheets
922 // accumulate into one buffer, allowing us to reduce how often new stylesheets
923 // are inserted in the browser. Appending a stylesheet and waiting for the
924 // browser to repaint is fairly expensive. (T47810)
926 // Don't extend the buffer if the item needs its own stylesheet.
927 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
928 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
929 // Linebreak for somewhat distinguishable sections
930 cssBuffer
+= '\n' + cssText
;
931 if ( !cssBufferTimer
) {
932 cssBufferTimer
= rAF( function () {
933 // Wrap in anonymous function that takes no arguments
934 // Support: Firefox < 13
935 // Firefox 12 has non-standard behaviour of passing a number
936 // as first argument to a setTimeout callback.
937 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
944 // This is a scheduled flush for the buffer
946 cssBufferTimer
= null;
951 // By default, always create a new <style>. Appending text to a <style> tag is
952 // is a performance anti-pattern as it requires CSS to be reparsed (T47810).
955 // Try to re-use existing <style> tags due to the IE stylesheet limit (T33676).
957 $style
= $( getMarker() ).prev();
958 // Verify that the element before the marker actually is a <style> tag created
959 // by mw.loader (not some other style tag, or e.g. a <meta> tag).
960 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) ) {
961 styleEl
= $style
[ 0 ];
962 styleEl
.appendChild( document
.createTextNode( cssText
) );
966 // Else: No existing tag to reuse. Continue below and create the first one.
969 $style
= $( newStyleTag( cssText
, getMarker() ) );
972 $style
.data( 'ResourceLoaderDynamicStyleTag', true );
980 * @param {Array} modules List of module names
981 * @return {string} Hash of concatenated version hashes.
983 function getCombinedVersion( modules
) {
984 var hashes
= $.map( modules
, function ( module
) {
985 return registry
[ module
].version
;
987 return fnv132( hashes
.join( '' ) );
991 * Determine whether all dependencies are in state 'ready', which means we may
992 * execute the module or job now.
995 * @param {Array} modules Names of modules to be checked
996 * @return {boolean} True if all modules are in state 'ready', false otherwise
998 function allReady( modules
) {
1000 for ( i
= 0; i
< modules
.length
; i
++ ) {
1001 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
1009 * Determine whether all dependencies are in state 'ready', which means we may
1010 * execute the module or job now.
1013 * @param {Array} modules Names of modules to be checked
1014 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1016 function anyFailed( modules
) {
1018 for ( i
= 0; i
< modules
.length
; i
++ ) {
1019 state
= mw
.loader
.getState( modules
[ i
] );
1020 if ( state
=== 'error' || state
=== 'missing' ) {
1028 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1029 * pending jobs and modules that depend upon this module. If the given module failed,
1030 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1031 * all jobs/modules now having their dependencies satisfied.
1033 * Jobs that depend on a failed module, will have their error callback ran (if any).
1036 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1038 function handlePending( module
) {
1039 var j
, job
, hasErrors
, m
, stateChange
;
1041 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1042 // If the current module failed, mark all dependent modules also as failed.
1043 // Iterate until steady-state to propagate the error state upwards in the
1046 stateChange
= false;
1047 for ( m
in registry
) {
1048 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1049 if ( anyFailed( registry
[ m
].dependencies
) ) {
1050 registry
[ m
].state
= 'error';
1055 } while ( stateChange
);
1058 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1059 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1060 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1061 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1062 // All dependencies satisfied, or some have errors
1064 jobs
.splice( j
, 1 );
1068 if ( typeof job
.error
=== 'function' ) {
1069 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1072 if ( typeof job
.ready
=== 'function' ) {
1077 // A user-defined callback raised an exception.
1078 // Swallow it to protect our state machine!
1079 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1084 if ( registry
[ module
].state
=== 'ready' ) {
1085 // The current module became 'ready'. Set it in the module store, and recursively execute all
1086 // dependent modules that are loaded and now have all dependencies satisfied.
1087 mw
.loader
.store
.set( module
, registry
[ module
] );
1088 for ( m
in registry
) {
1089 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1097 * Resolve dependencies and detect circular references.
1100 * @param {string} module Name of the top-level module whose dependencies shall be
1101 * resolved and sorted.
1102 * @param {Array} resolved Returns a topological sort of the given module and its
1103 * dependencies, such that later modules depend on earlier modules. The array
1104 * contains the module names. If the array contains already some module names,
1105 * this function appends its result to the pre-existing array.
1106 * @param {StringSet} [unresolved] Used to track the current dependency
1107 * chain, and to report loops in the dependency graph.
1108 * @throws {Error} If any unregistered module or a dependency loop is encountered
1110 function sortDependencies( module
, resolved
, unresolved
) {
1113 if ( !hasOwn
.call( registry
, module
) ) {
1114 throw new Error( 'Unknown dependency: ' + module
);
1117 if ( registry
[ module
].skip
!== null ) {
1118 // eslint-disable-next-line no-new-func
1119 skip
= new Function( registry
[ module
].skip
);
1120 registry
[ module
].skip
= null;
1122 registry
[ module
].skipped
= true;
1123 registry
[ module
].dependencies
= [];
1124 registry
[ module
].state
= 'ready';
1125 handlePending( module
);
1130 // Resolves dynamic loader function and replaces it with its own results
1131 if ( typeof registry
[ module
].dependencies
=== 'function' ) {
1132 registry
[ module
].dependencies
= registry
[ module
].dependencies();
1133 // Ensures the module's dependencies are always in an array
1134 if ( typeof registry
[ module
].dependencies
!== 'object' ) {
1135 registry
[ module
].dependencies
= [ registry
[ module
].dependencies
];
1138 if ( $.inArray( module
, resolved
) !== -1 ) {
1139 // Module already resolved; nothing to do
1142 // Create unresolved if not passed in
1143 if ( !unresolved
) {
1144 unresolved
= new StringSet();
1146 // Tracks down dependencies
1147 deps
= registry
[ module
].dependencies
;
1148 for ( i
= 0; i
< deps
.length
; i
++ ) {
1149 if ( $.inArray( deps
[ i
], resolved
) === -1 ) {
1150 if ( unresolved
.has( deps
[ i
] ) ) {
1151 throw new Error( mw
.format(
1152 'Circular reference detected: $1 -> $2',
1158 unresolved
.add( module
);
1159 sortDependencies( deps
[ i
], resolved
, unresolved
);
1162 resolved
.push( module
);
1166 * Get names of module that a module depends on, in their proper dependency order.
1169 * @param {string[]} modules Array of string module names
1170 * @return {Array} List of dependencies, including 'module'.
1172 function resolve( modules
) {
1174 $.each( modules
, function ( idx
, module
) {
1175 sortDependencies( module
, resolved
);
1181 * Load and execute a script.
1184 * @param {string} src URL to script, will be used as the src attribute in the script tag
1185 * @return {jQuery.Promise}
1187 function addScript( src
) {
1191 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1192 // XHR for a same domain request instead of <script>, which changes the request
1193 // headers (potentially missing a cache hit), and reduces caching in general
1194 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1195 // text, so we'd need to $.globalEval, which then messes up line numbers.
1202 * Queue the loading and execution of a script for a particular module.
1205 * @param {string} src URL of the script
1206 * @param {string} [moduleName] Name of currently executing module
1207 * @return {jQuery.Promise}
1209 function queueModuleScript( src
, moduleName
) {
1210 var r
= $.Deferred();
1212 pendingRequests
.push( function () {
1213 if ( moduleName
&& hasOwn
.call( registry
, moduleName
) ) {
1214 // Emulate runScript() part of execute()
1215 window
.require
= mw
.loader
.require
;
1216 window
.module
= registry
[ moduleName
].module
;
1218 addScript( src
).always( function () {
1219 // 'module.exports' should not persist after the file is executed to
1220 // avoid leakage to unrelated code. 'require' should be kept, however,
1221 // as asynchronous access to 'require' is allowed and expected. (T144879)
1222 delete window
.module
;
1225 // Start the next one (if any)
1226 if ( pendingRequests
[ 0 ] ) {
1227 pendingRequests
.shift()();
1229 handlingPendingRequests
= false;
1233 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1234 handlingPendingRequests
= true;
1235 pendingRequests
.shift()();
1241 * Utility function for execute()
1245 function addLink( media
, url
) {
1246 var el
= document
.createElement( 'link' );
1248 el
.rel
= 'stylesheet';
1249 if ( media
&& media
!== 'all' ) {
1252 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1253 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1256 $( getMarker() ).before( el
);
1260 * Executes a loaded module, making it ready to use
1263 * @param {string} module Module name to execute
1265 function execute( module
) {
1266 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1267 cssHandlesRegistered
= false;
1269 if ( !hasOwn
.call( registry
, module
) ) {
1270 throw new Error( 'Module has not been registered yet: ' + module
);
1272 if ( registry
[ module
].state
!== 'loaded' ) {
1273 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1276 registry
[ module
].state
= 'executing';
1278 runScript = function () {
1279 var script
, markModuleReady
, nestedAddScript
, legacyWait
, implicitDependencies
,
1280 // Expand to include dependencies since we have to exclude both legacy modules
1281 // and their dependencies from the legacyWait (to prevent a circular dependency).
1282 legacyModules
= resolve( mw
.config
.get( 'wgResourceLoaderLegacyModules', [] ) );
1284 script
= registry
[ module
].script
;
1285 markModuleReady = function () {
1286 registry
[ module
].state
= 'ready';
1287 handlePending( module
);
1289 nestedAddScript = function ( arr
, callback
, i
) {
1290 // Recursively call queueModuleScript() in its own callback
1291 // for each element of arr.
1292 if ( i
>= arr
.length
) {
1293 // We're at the end of the array
1298 queueModuleScript( arr
[ i
], module
).always( function () {
1299 nestedAddScript( arr
, callback
, i
+ 1 );
1303 implicitDependencies
= ( $.inArray( module
, legacyModules
) !== -1 ) ?
1307 if ( module
=== 'user' ) {
1308 // Implicit dependency on the site module. Not real dependency because
1309 // it should run after 'site' regardless of whether it succeeds or fails.
1310 implicitDependencies
.push( 'site' );
1313 legacyWait
= implicitDependencies
.length
?
1314 mw
.loader
.using( implicitDependencies
) :
1315 $.Deferred().resolve();
1317 legacyWait
.always( function () {
1319 if ( $.isArray( script
) ) {
1320 nestedAddScript( script
, markModuleReady
, 0 );
1321 } else if ( typeof script
=== 'function' ) {
1322 // Pass jQuery twice so that the signature of the closure which wraps
1323 // the script can bind both '$' and 'jQuery'.
1324 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1327 } else if ( typeof script
=== 'string' ) {
1328 // Site and user modules are legacy scripts that run in the global scope.
1329 // This is transported as a string instead of a function to avoid needing
1330 // to use string manipulation to undo the function wrapper.
1331 $.globalEval( script
);
1335 // Module without script
1339 // Use mw.track instead of mw.log because these errors are common in production mode
1340 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1341 registry
[ module
].state
= 'error';
1342 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1343 handlePending( module
);
1348 // Add localizations to message system
1349 if ( registry
[ module
].messages
) {
1350 mw
.messages
.set( registry
[ module
].messages
);
1353 // Initialise templates
1354 if ( registry
[ module
].templates
) {
1355 mw
.templates
.set( module
, registry
[ module
].templates
);
1358 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1361 checkCssHandles = function () {
1362 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1363 // one of the cssHandles is fired while we're still creating more handles.
1364 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1366 runScript
= undefined; // Revoke
1369 cssHandle = function () {
1370 var check
= checkCssHandles
;
1372 return function () {
1376 check
= undefined; // Revoke
1382 // Process styles (see also mw.loader.implement)
1383 // * back-compat: { <media>: css }
1384 // * back-compat: { <media>: [url, ..] }
1385 // * { "css": [css, ..] }
1386 // * { "url": { <media>: [url, ..] } }
1387 if ( registry
[ module
].style
) {
1388 for ( key
in registry
[ module
].style
) {
1389 value
= registry
[ module
].style
[ key
];
1392 if ( key
!== 'url' && key
!== 'css' ) {
1393 // Backwards compatibility, key is a media-type
1394 if ( typeof value
=== 'string' ) {
1395 // back-compat: { <media>: css }
1396 // Ignore 'media' because it isn't supported (nor was it used).
1397 // Strings are pre-wrapped in "@media". The media-type was just ""
1398 // (because it had to be set to something).
1399 // This is one of the reasons why this format is no longer used.
1400 addEmbeddedCSS( value
, cssHandle() );
1402 // back-compat: { <media>: [url, ..] }
1408 // Array of css strings in key 'css',
1409 // or back-compat array of urls from media-type
1410 if ( $.isArray( value
) ) {
1411 for ( i
= 0; i
< value
.length
; i
++ ) {
1412 if ( key
=== 'bc-url' ) {
1413 // back-compat: { <media>: [url, ..] }
1414 addLink( media
, value
[ i
] );
1415 } else if ( key
=== 'css' ) {
1416 // { "css": [css, ..] }
1417 addEmbeddedCSS( value
[ i
], cssHandle() );
1420 // Not an array, but a regular object
1421 // Array of urls inside media-type key
1422 } else if ( typeof value
=== 'object' ) {
1423 // { "url": { <media>: [url, ..] } }
1424 for ( media
in value
) {
1425 urls
= value
[ media
];
1426 for ( i
= 0; i
< urls
.length
; i
++ ) {
1427 addLink( media
, urls
[ i
] );
1435 cssHandlesRegistered
= true;
1440 * Add one or more modules to the module load queue.
1445 * @param {string|string[]} dependencies Module name or array of string module names
1446 * @param {Function} [ready] Callback to execute when all dependencies are ready
1447 * @param {Function} [error] Callback to execute when any dependency fails
1449 function enqueue( dependencies
, ready
, error
) {
1450 // Allow calling by single module name
1451 if ( typeof dependencies
=== 'string' ) {
1452 dependencies
= [ dependencies
];
1455 // Add ready and error callbacks if they were given
1456 if ( ready
!== undefined || error
!== undefined ) {
1458 // Narrow down the list to modules that are worth waiting for
1459 dependencies
: $.grep( dependencies
, function ( module
) {
1460 var state
= mw
.loader
.getState( module
);
1461 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1468 $.each( dependencies
, function ( idx
, module
) {
1469 var state
= mw
.loader
.getState( module
);
1470 // Only queue modules that are still in the initial 'registered' state
1471 // (not ones already loading, ready or error).
1472 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1473 // Private modules must be embedded in the page. Don't bother queuing
1474 // these as the server will deny them anyway (T101806).
1475 if ( registry
[ module
].group
=== 'private' ) {
1476 registry
[ module
].state
= 'error';
1477 handlePending( module
);
1480 queue
.push( module
);
1487 function sortQuery( o
) {
1493 if ( hasOwn
.call( o
, key
) ) {
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
1510 function buildModulesString( moduleMap
) {
1514 for ( prefix
in moduleMap
) {
1515 p
= prefix
=== '' ? '' : prefix
+ '.';
1516 arr
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1518 return arr
.join( '|' );
1522 * Make a network request to load modules from the server.
1525 * @param {Object} moduleMap Module map, see #buildModulesString
1526 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1527 * @param {string} sourceLoadScript URL of load.php
1529 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
1530 var query
= $.extend(
1531 { modules
: buildModulesString( moduleMap
) },
1534 query
= sortQuery( query
);
1535 addScript( sourceLoadScript
+ '?' + $.param( query
) );
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
, l
,
1579 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1581 if ( !batch
.length
) {
1585 // Always order modules alphabetically to help reduce cache
1586 // misses for otherwise identical content.
1589 // Build a list of query parameters common to all requests
1591 skin
: mw
.config
.get( 'skin' ),
1592 lang
: mw
.config
.get( 'wgUserLanguage' ),
1593 debug
: mw
.config
.get( 'debug' )
1595 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1597 // Split module list by source and by group.
1599 for ( b
= 0; b
< batch
.length
; b
++ ) {
1600 bSource
= registry
[ batch
[ b
] ].source
;
1601 bGroup
= registry
[ batch
[ b
] ].group
;
1602 if ( !hasOwn
.call( splits
, bSource
) ) {
1603 splits
[ bSource
] = {};
1605 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1606 splits
[ bSource
][ bGroup
] = [];
1608 bSourceGroup
= splits
[ bSource
][ bGroup
];
1609 bSourceGroup
.push( batch
[ b
] );
1612 for ( source
in splits
) {
1614 sourceLoadScript
= sources
[ source
];
1616 for ( group
in splits
[ source
] ) {
1618 // Cache access to currently selected list of
1619 // modules for this group from this source.
1620 modules
= splits
[ source
][ group
];
1622 currReqBase
= $.extend( {
1623 version
: getCombinedVersion( modules
)
1625 // For user modules append a user name to the query string.
1626 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1627 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1629 currReqBaseLength
= $.param( currReqBase
).length
;
1630 // We may need to split up the request to honor the query string length limit,
1631 // so build it piece by piece.
1632 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1634 moduleMap
= {}; // { prefix: [ suffixes ] }
1636 for ( i
= 0; i
< modules
.length
; i
++ ) {
1637 // Determine how many bytes this module would add to the query string
1638 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1640 // If lastDotIndex is -1, substr() returns an empty string
1641 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1642 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1644 bytesAdded
= hasOwn
.call( moduleMap
, prefix
) ?
1645 suffix
.length
+ 3 : // '%2C'.length == 3
1646 modules
[ i
].length
+ 3; // '%7C'.length == 3
1648 // If the url would become too long, create a new one,
1649 // but don't create empty requests
1650 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1651 // This url would become too long, create a new one, and start the old one
1652 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1654 l
= currReqBaseLength
+ 9;
1655 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1657 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1658 moduleMap
[ prefix
] = [];
1660 moduleMap
[ prefix
].push( suffix
);
1663 // If there's anything left in moduleMap, request that too
1664 if ( !$.isEmptyObject( moduleMap
) ) {
1665 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1673 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1674 * form of calls to mw.loader#implement().
1675 * @param {Function} cb Callback in case of failure
1676 * @param {Error} cb.err
1678 function asyncEval( implementations
, cb
) {
1679 if ( !implementations
.length
) {
1682 mw
.requestIdleCallback( function () {
1684 $.globalEval( implementations
.join( ';' ) );
1692 * Make a versioned key for a specific module.
1695 * @param {string} module Module name
1696 * @return {string|null} Module key in format '`[name]@[version]`',
1697 * or null if the module does not exist
1699 function getModuleKey( module
) {
1700 return hasOwn
.call( registry
, module
) ?
1701 ( module
+ '@' + registry
[ module
].version
) : null;
1706 * @param {string} key Module name or '`[name]@[version]`'
1709 function splitModuleKey( key
) {
1710 var index
= key
.indexOf( '@' );
1711 if ( index
=== -1 ) {
1712 return { name
: key
};
1715 name
: key
.slice( 0, index
),
1716 version
: key
.slice( index
+ 1 )
1720 /* Public Members */
1723 * The module registry is exposed as an aid for debugging and inspecting page
1724 * state; it is not a public interface for modifying the registry.
1730 moduleRegistry
: registry
,
1733 * @inheritdoc #newStyleTag
1736 addStyleTag
: newStyleTag
,
1739 * Start loading of all queued module dependencies.
1744 var q
, batch
, implementations
, sourceModules
;
1748 // Appends a list of modules from the queue to the batch
1749 for ( q
= 0; q
< queue
.length
; q
++ ) {
1750 // Only load modules which are registered
1751 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1752 // Prevent duplicate entries
1753 if ( $.inArray( queue
[ q
], batch
) === -1 ) {
1754 batch
.push( queue
[ q
] );
1755 // Mark registered modules as loading
1756 registry
[ queue
[ q
] ].state
= 'loading';
1761 // Now that the queue has been processed into a batch, clear the queue.
1762 // This MUST happen before we initiate any eval or network request. Otherwise,
1763 // it is possible for a cached script to instantly trigger the same work queue
1764 // again; all before we've cleared it causing each request to include modules
1765 // which are already loaded.
1768 if ( !batch
.length
) {
1772 mw
.loader
.store
.init();
1773 if ( mw
.loader
.store
.enabled
) {
1774 implementations
= [];
1776 batch
= $.grep( batch
, function ( module
) {
1777 var implementation
= mw
.loader
.store
.get( module
);
1778 if ( implementation
) {
1779 implementations
.push( implementation
);
1780 sourceModules
.push( module
);
1785 asyncEval( implementations
, function ( err
) {
1787 // Not good, the cached mw.loader.implement calls failed! This should
1788 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1789 // Depending on how corrupt the string is, it is likely that some
1790 // modules' implement() succeeded while the ones after the error will
1791 // never run and leave their modules in the 'loading' state forever.
1792 mw
.loader
.store
.stats
.failed
++;
1794 // Since this is an error not caused by an individual module but by
1795 // something that infected the implement call itself, don't take any
1796 // risks and clear everything in this cache.
1797 mw
.loader
.store
.clear();
1799 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1800 // Re-add the failed ones that are still pending back to the batch
1801 failed
= $.grep( sourceModules
, function ( module
) {
1802 return registry
[ module
].state
=== 'loading';
1804 batchRequest( failed
);
1808 batchRequest( batch
);
1812 * Register a source.
1814 * The #work() method will use this information to split up requests by source.
1816 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1818 * @param {string|Object} id Source ID, or object mapping ids to load urls
1819 * @param {string} loadUrl Url to a load.php end point
1820 * @throws {Error} If source id is already registered
1822 addSource: function ( id
, loadUrl
) {
1824 // Allow multiple additions
1825 if ( typeof id
=== 'object' ) {
1826 for ( source
in id
) {
1827 mw
.loader
.addSource( source
, id
[ source
] );
1832 if ( hasOwn
.call( sources
, id
) ) {
1833 throw new Error( 'source already registered: ' + id
);
1836 sources
[ id
] = loadUrl
;
1840 * Register a module, letting the system know about it and its properties.
1842 * The startup modules contain calls to this method.
1844 * When using multiple module registration by passing an array, dependencies that
1845 * are specified as references to modules within the array will be resolved before
1846 * the modules are registered.
1848 * @param {string|Array} module Module name or array of arrays, each containing
1849 * a list of arguments compatible with this method
1850 * @param {string|number} version Module version hash (falls backs to empty string)
1851 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1852 * @param {string|Array|Function} dependencies One string or array of strings of module
1853 * names on which this module depends, or a function that returns that array.
1854 * @param {string} [group=null] Group which the module is in
1855 * @param {string} [source='local'] Name of the source
1856 * @param {string} [skip=null] Script body of the skip function
1858 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1860 // Allow multiple registration
1861 if ( typeof module
=== 'object' ) {
1862 resolveIndexedDependencies( module
);
1863 for ( i
= 0; i
< module
.length
; i
++ ) {
1864 // module is an array of module names
1865 if ( typeof module
[ i
] === 'string' ) {
1866 mw
.loader
.register( module
[ i
] );
1867 // module is an array of arrays
1868 } else if ( typeof module
[ i
] === 'object' ) {
1869 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1874 if ( hasOwn
.call( registry
, module
) ) {
1875 throw new Error( 'module already registered: ' + module
);
1877 if ( typeof dependencies
=== 'string' ) {
1878 // A single module name
1879 deps
= [ dependencies
];
1880 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
1881 // Array of module names or a function that returns an array
1882 deps
= dependencies
;
1884 // List the module as registered
1885 registry
[ module
] = {
1886 // Exposed to execute() for mw.loader.implement() closures.
1887 // Import happens via require().
1891 version
: version
!== undefined ? String( version
) : '',
1892 dependencies
: deps
|| [],
1893 group
: typeof group
=== 'string' ? group
: null,
1894 source
: typeof source
=== 'string' ? source
: 'local',
1895 state
: 'registered',
1896 skip
: typeof skip
=== 'string' ? skip
: null
1901 * Implement a module given the components that make up the module.
1903 * When #load() or #using() requests one or more modules, the server
1904 * response contain calls to this function.
1906 * @param {string} module Name of module and current module version. Formatted
1907 * as '`[name]@[version]`". This version should match the requested version
1908 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1909 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1910 * @param {Function|Array|string} [script] Function with module code, list of URLs
1911 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1912 * @param {Object} [style] Should follow one of the following patterns:
1914 * { "css": [css, ..] }
1915 * { "url": { <media>: [url, ..] } }
1917 * And for backwards compatibility (needs to be supported forever due to caching):
1920 * { <media>: [url, ..] }
1922 * The reason css strings are not concatenated anymore is bug 31676. We now check
1923 * whether it's safe to extend the stylesheet.
1926 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1927 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1929 implement: function ( module
, script
, style
, messages
, templates
) {
1930 var split
= splitModuleKey( module
),
1932 version
= split
.version
;
1933 // Automatically register module
1934 if ( !hasOwn
.call( registry
, name
) ) {
1935 mw
.loader
.register( name
);
1937 // Check for duplicate implementation
1938 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1939 throw new Error( 'module already implemented: ' + name
);
1942 // Without this reset, if there is a version mismatch between the
1943 // requested and received module version, then mw.loader.store would
1944 // cache the response under the requested key. Thus poisoning the cache
1945 // indefinitely with a stale value. (T117587)
1946 registry
[ name
].version
= version
;
1948 // Attach components
1949 registry
[ name
].script
= script
|| null;
1950 registry
[ name
].style
= style
|| null;
1951 registry
[ name
].messages
= messages
|| null;
1952 registry
[ name
].templates
= templates
|| null;
1953 // The module may already have been marked as erroneous
1954 if ( $.inArray( registry
[ name
].state
, [ 'error', 'missing' ] ) === -1 ) {
1955 registry
[ name
].state
= 'loaded';
1956 if ( allReady( registry
[ name
].dependencies
) ) {
1963 * Execute a function as soon as one or more required modules are ready.
1965 * Example of inline dependency on OOjs:
1967 * mw.loader.using( 'oojs', function () {
1968 * OO.compare( [ 1 ], [ 1 ] );
1971 * Since MediaWiki 1.23 this also returns a promise.
1973 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1975 * @param {string|Array} dependencies Module name or array of modules names the
1976 * callback depends on to be ready before executing
1977 * @param {Function} [ready] Callback to execute when all dependencies are ready
1978 * @param {Function} [error] Callback to execute if one or more dependencies failed
1979 * @return {jQuery.Promise} With a `require` function
1981 using: function ( dependencies
, ready
, error
) {
1982 var deferred
= $.Deferred();
1984 // Allow calling with a single dependency as a string
1985 if ( typeof dependencies
=== 'string' ) {
1986 dependencies
= [ dependencies
];
1990 deferred
.done( ready
);
1993 deferred
.fail( error
);
1996 // Resolve entire dependency map
1997 dependencies
= resolve( dependencies
);
1998 if ( allReady( dependencies
) ) {
1999 // Run ready immediately
2000 deferred
.resolve( mw
.loader
.require
);
2001 } else if ( anyFailed( dependencies
) ) {
2002 // Execute error immediately if any dependencies have errors
2004 new Error( 'One or more dependencies failed to load' ),
2008 // Not all dependencies are ready, add to the load queue
2009 enqueue( dependencies
, function () {
2010 deferred
.resolve( mw
.loader
.require
);
2011 }, deferred
.reject
);
2014 return deferred
.promise();
2018 * Load an external script or one or more modules.
2020 * @param {string|Array} modules Either the name of a module, array of modules,
2021 * or a URL of an external script or style
2022 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2023 * external script or style; acceptable values are "text/css" and
2024 * "text/javascript"; if no type is provided, text/javascript is assumed.
2026 load: function ( modules
, type
) {
2029 // Allow calling with a url or single dependency as a string
2030 if ( typeof modules
=== 'string' ) {
2031 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2032 if ( /^(https?:)?\/?\//.test( modules
) ) {
2033 if ( type
=== 'text/css' ) {
2035 // Use properties instead of attributes as IE throws security
2036 // warnings when inserting a <link> tag with a protocol-relative
2037 // URL set though attributes - when on HTTPS. See bug 41331.
2038 l
= document
.createElement( 'link' );
2039 l
.rel
= 'stylesheet';
2041 $( 'head' ).append( l
);
2044 if ( type
=== 'text/javascript' || type
=== undefined ) {
2045 addScript( modules
);
2049 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2051 // Called with single module
2052 modules
= [ modules
];
2055 // Filter out undefined modules, otherwise resolve() will throw
2056 // an exception for trying to load an undefined module.
2057 // Undefined modules are acceptable here in load(), because load() takes
2058 // an array of unrelated modules, whereas the modules passed to
2059 // using() are related and must all be loaded.
2060 filtered
= $.grep( modules
, function ( module
) {
2061 var state
= mw
.loader
.getState( module
);
2062 return state
!== null && state
!== 'error' && state
!== 'missing';
2065 if ( filtered
.length
=== 0 ) {
2068 // Resolve entire dependency map
2069 filtered
= resolve( filtered
);
2070 // If all modules are ready, or if any modules have errors, nothing to be done.
2071 if ( allReady( filtered
) || anyFailed( filtered
) ) {
2074 // Some modules are not yet ready, add to module load queue.
2075 enqueue( filtered
, undefined, undefined );
2079 * Change the state of one or more modules.
2081 * @param {string|Object} module Module name or object of module name/state pairs
2082 * @param {string} state State name
2084 state: function ( module
, state
) {
2087 if ( typeof module
=== 'object' ) {
2088 for ( m
in module
) {
2089 mw
.loader
.state( m
, module
[ m
] );
2093 if ( !hasOwn
.call( registry
, module
) ) {
2094 mw
.loader
.register( module
);
2096 registry
[ module
].state
= state
;
2097 if ( $.inArray( state
, [ 'ready', 'error', 'missing' ] ) !== -1 ) {
2098 // Make sure pending modules depending on this one get executed if their
2099 // dependencies are now fulfilled!
2100 handlePending( module
);
2105 * Get the version of a module.
2107 * @param {string} module Name of module
2108 * @return {string|null} The version, or null if the module (or its version) is not
2111 getVersion: function ( module
) {
2112 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].version
=== undefined ) {
2115 return registry
[ module
].version
;
2119 * Get the state of a module.
2121 * @param {string} module Name of module
2122 * @return {string|null} The state, or null if the module (or its state) is not
2125 getState: function ( module
) {
2126 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].state
=== undefined ) {
2129 return registry
[ module
].state
;
2133 * Get the names of all registered modules.
2137 getModuleNames: function () {
2138 return $.map( registry
, function ( i
, key
) {
2144 * Get the exported value of a module.
2146 * Modules may provide this via their local `module.exports`.
2151 require: function ( moduleName
) {
2152 var state
= mw
.loader
.getState( moduleName
);
2154 // Only ready modules can be required
2155 if ( state
!== 'ready' ) {
2156 // Module may've forgotten to declare a dependency
2157 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2160 return registry
[ moduleName
].module
.exports
;
2164 * @inheritdoc mw.inspect#runReports
2167 inspect: function () {
2168 var args
= slice
.call( arguments
);
2169 mw
.loader
.using( 'mediawiki.inspect', function () {
2170 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2175 * On browsers that implement the localStorage API, the module store serves as a
2176 * smart complement to the browser cache. Unlike the browser cache, the module store
2177 * can slice a concatenated response from ResourceLoader into its constituent
2178 * modules and cache each of them separately, using each module's versioning scheme
2179 * to determine when the cache should be invalidated.
2182 * @class mw.loader.store
2185 // Whether the store is in use on this page.
2188 MODULE_SIZE_MAX
: 100 * 1000,
2190 // The contents of the store, mapping '[name]@[version]' keys
2191 // to module implementations.
2195 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2198 * Construct a JSON-serializable object representing the content of the store.
2200 * @return {Object} Module store contents.
2202 toJSON: function () {
2203 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2207 * Get the localStorage key for the entire module store. The key references
2208 * $wgDBname to prevent clashes between wikis which share a common host.
2210 * @return {string} localStorage item key
2212 getStoreKey: function () {
2213 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2217 * Get a key on which to vary the module cache.
2219 * @return {string} String of concatenated vary conditions.
2221 getVary: function () {
2223 mw
.config
.get( 'skin' ),
2224 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2225 mw
.config
.get( 'wgUserLanguage' )
2230 * Initialize the store.
2232 * Retrieves store from localStorage and (if successfully retrieved) decoding
2233 * the stored JSON value to a plain object.
2235 * The try / catch block is used for JSON & localStorage feature detection.
2236 * See the in-line documentation for Modernizr's localStorage feature detection
2237 * code for a full account of why we need a try / catch:
2238 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2243 if ( mw
.loader
.store
.enabled
!== null ) {
2249 // Disabled because localStorage quotas are tight and (in Firefox's case)
2250 // shared by multiple origins.
2251 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2252 /Firefox|Opera/.test( navigator
.userAgent
) ||
2254 // Disabled by configuration.
2255 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2257 // Clear any previous store to free up space. (T66721)
2258 mw
.loader
.store
.clear();
2259 mw
.loader
.store
.enabled
= false;
2262 if ( mw
.config
.get( 'debug' ) ) {
2263 // Disable module store in debug mode
2264 mw
.loader
.store
.enabled
= false;
2269 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2270 // If we get here, localStorage is available; mark enabled
2271 mw
.loader
.store
.enabled
= true;
2272 data
= JSON
.parse( raw
);
2273 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2274 mw
.loader
.store
.items
= data
.items
;
2278 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2281 if ( raw
=== undefined ) {
2282 // localStorage failed; disable store
2283 mw
.loader
.store
.enabled
= false;
2285 mw
.loader
.store
.update();
2290 * Retrieve a module from the store and update cache hit stats.
2292 * @param {string} module Module name
2293 * @return {string|boolean} Module implementation or false if unavailable
2295 get: function ( module
) {
2298 if ( !mw
.loader
.store
.enabled
) {
2302 key
= getModuleKey( module
);
2303 if ( key
in mw
.loader
.store
.items
) {
2304 mw
.loader
.store
.stats
.hits
++;
2305 return mw
.loader
.store
.items
[ key
];
2307 mw
.loader
.store
.stats
.misses
++;
2312 * Stringify a module and queue it for storage.
2314 * @param {string} module Module name
2315 * @param {Object} descriptor The module's descriptor as set in the registry
2317 set: function ( module
, descriptor
) {
2320 if ( !mw
.loader
.store
.enabled
) {
2324 key
= getModuleKey( module
);
2327 // Already stored a copy of this exact version
2328 key
in mw
.loader
.store
.items
||
2329 // Module failed to load
2330 descriptor
.state
!== 'ready' ||
2331 // Unversioned, private, or site-/user-specific
2332 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user' ] ) !== -1 ) ||
2333 // Partial descriptor
2334 // (e.g. skipped module, or style module with state=ready)
2335 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2336 descriptor
.messages
, descriptor
.templates
] ) !== -1
2344 JSON
.stringify( key
),
2345 typeof descriptor
.script
=== 'function' ?
2346 String( descriptor
.script
) :
2347 JSON
.stringify( descriptor
.script
),
2348 JSON
.stringify( descriptor
.style
),
2349 JSON
.stringify( descriptor
.messages
),
2350 JSON
.stringify( descriptor
.templates
)
2352 // Attempted workaround for a possible Opera bug (bug T59567).
2353 // This regex should never match under sane conditions.
2354 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2355 args
[ 1 ] = 'function' + args
[ 1 ];
2356 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2359 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2363 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2364 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2367 mw
.loader
.store
.items
[ key
] = src
;
2368 mw
.loader
.store
.update();
2372 * Iterate through the module store, removing any item that does not correspond
2373 * (in name and version) to an item in the module registry.
2375 prune: function () {
2378 if ( !mw
.loader
.store
.enabled
) {
2382 for ( key
in mw
.loader
.store
.items
) {
2383 module
= key
.slice( 0, key
.indexOf( '@' ) );
2384 if ( getModuleKey( module
) !== key
) {
2385 mw
.loader
.store
.stats
.expired
++;
2386 delete mw
.loader
.store
.items
[ key
];
2387 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2388 // This value predates the enforcement of a size limit on cached modules.
2389 delete mw
.loader
.store
.items
[ key
];
2395 * Clear the entire module store right now.
2397 clear: function () {
2398 mw
.loader
.store
.items
= {};
2400 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2401 } catch ( ignored
) {}
2405 * Sync in-memory store back to localStorage.
2407 * This function debounces updates. When called with a flush already pending,
2408 * the call is coalesced into the pending update. The call to
2409 * localStorage.setItem will be naturally deferred until the page is quiescent.
2411 * Because localStorage is shared by all pages from the same origin, if multiple
2412 * pages are loaded with different module sets, the possibility exists that
2413 * modules saved by one page will be clobbered by another. But the impact would
2414 * be minor and the problem would be corrected by subsequent page views.
2418 update
: ( function () {
2419 var hasPendingWrite
= false;
2421 function flushWrites() {
2423 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2427 mw
.loader
.store
.prune();
2428 key
= mw
.loader
.store
.getStoreKey();
2430 // Replacing the content of the module store might fail if the new
2431 // contents would exceed the browser's localStorage size limit. To
2432 // avoid clogging the browser with stale data, always remove the old
2433 // value before attempting to set the new one.
2434 localStorage
.removeItem( key
);
2435 data
= JSON
.stringify( mw
.loader
.store
);
2436 localStorage
.setItem( key
, data
);
2438 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2441 hasPendingWrite
= false;
2444 return function () {
2445 if ( !hasPendingWrite
) {
2446 hasPendingWrite
= true;
2447 mw
.requestIdleCallback( flushWrites
);
2456 * HTML construction helper functions
2463 * output = Html.element( 'div', {}, new Html.Raw(
2464 * Html.element( 'img', { src: '<' } )
2466 * mw.log( output ); // <div><img src="<"/></div>
2471 html
: ( function () {
2472 function escapeCallback( s
) {
2489 * Escape a string for HTML.
2491 * Converts special characters to HTML entities.
2493 * mw.html.escape( '< > \' & "' );
2494 * // Returns < > ' & "
2496 * @param {string} s The string to escape
2497 * @return {string} HTML
2499 escape: function ( s
) {
2500 return s
.replace( /['"<>&]/g, escapeCallback
);
2504 * Create an HTML element string, with safe escaping.
2506 * @param {string} name The tag name.
2507 * @param {Object} [attrs] An object with members mapping element names to values
2508 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2510 * - string: Text to be escaped.
2511 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2512 * - this.Raw: The raw value is directly included.
2513 * - this.Cdata: The raw value is directly included. An exception is
2514 * thrown if it contains any illegal ETAGO delimiter.
2515 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2516 * @return {string} HTML
2518 element: function ( name
, attrs
, contents
) {
2519 var v
, attrName
, s
= '<' + name
;
2522 for ( attrName
in attrs
) {
2523 v
= attrs
[ attrName
];
2524 // Convert name=true, to name=name
2528 } else if ( v
=== false ) {
2531 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2534 if ( contents
=== undefined || contents
=== null ) {
2541 switch ( typeof contents
) {
2544 s
+= this.escape( contents
);
2548 // Convert to string
2549 s
+= String( contents
);
2552 if ( contents
instanceof this.Raw
) {
2553 // Raw HTML inclusion
2554 s
+= contents
.value
;
2555 } else if ( contents
instanceof this.Cdata
) {
2557 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2558 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2560 s
+= contents
.value
;
2562 throw new Error( 'mw.html.element: Invalid type of contents' );
2565 s
+= '</' + name
+ '>';
2570 * Wrapper object for raw HTML passed to mw.html.element().
2572 * @class mw.html.Raw
2574 Raw: function ( value
) {
2579 * Wrapper object for CDATA element contents passed to mw.html.element()
2581 * @class mw.html.Cdata
2583 Cdata: function ( value
) {
2589 // Skeleton user object, extended by the 'mediawiki.user' module.
2596 * @property {mw.Map}
2600 * @property {mw.Map}
2605 // OOUI widgets specific to MediaWiki
2609 * Registry and firing of events.
2611 * MediaWiki has various interface components that are extended, enhanced
2612 * or manipulated in some other way by extensions, gadgets and even
2615 * This framework helps streamlining the timing of when these other
2616 * code paths fire their plugins (instead of using document-ready,
2617 * which can and should be limited to firing only once).
2619 * Features like navigating to other wiki pages, previewing an edit
2620 * and editing itself – without a refresh – can then retrigger these
2621 * hooks accordingly to ensure everything still works as expected.
2625 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2626 * mw.hook( 'wikipage.content' ).fire( $content );
2628 * Handlers can be added and fired for arbitrary event names at any time. The same
2629 * event can be fired multiple times. The last run of an event is memorized
2630 * (similar to `$(document).ready` and `$.Deferred().done`).
2631 * This means if an event is fired, and a handler added afterwards, the added
2632 * function will be fired right away with the last given event data.
2634 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2635 * Thus allowing flexible use and optimal maintainability and authority control.
2636 * You can pass around the `add` and/or `fire` method to another piece of code
2637 * without it having to know the event name (or `mw.hook` for that matter).
2639 * var h = mw.hook( 'bar.ready' );
2640 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2642 * Note: Events are documented with an underscore instead of a dot in the event
2643 * name due to jsduck not supporting dots in that position.
2647 hook
: ( function () {
2651 * Create an instance of mw.hook.
2655 * @param {string} name Name of hook.
2658 return function ( name
) {
2659 var list
= hasOwn
.call( lists
, name
) ?
2661 lists
[ name
] = $.Callbacks( 'memory' );
2665 * Register a hook handler
2667 * @param {...Function} handler Function to bind.
2673 * Unregister a hook handler
2675 * @param {...Function} handler Function to unbind.
2678 remove
: list
.remove
,
2683 * @param {...Mixed} data
2687 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2694 // Alias $j to jQuery for backwards compatibility
2695 // @deprecated since 1.23 Use $ or jQuery instead
2696 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2699 * Log a message to window.console, if possible.
2701 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2702 * also in production mode). Gets console references in each invocation instead of caching the
2703 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2706 * @param {string} topic Stream name passed by mw.track
2707 * @param {Object} data Data passed by mw.track
2708 * @param {Error} [data.exception]
2709 * @param {string} data.source Error source
2710 * @param {string} [data.module] Name of module which caused the error
2712 function logError( topic
, data
) {
2715 source
= data
.source
,
2716 module
= data
.module
,
2717 console
= window
.console
;
2719 if ( console
&& console
.log
) {
2720 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2722 msg
+= ' in module ' + module
;
2724 msg
+= ( e
? ':' : '.' );
2727 // If we have an exception object, log it to the error channel to trigger
2728 // proper stacktraces in browsers that support it. No fallback as we have
2729 // no browsers that don't support error(), but do support log().
2730 if ( e
&& console
.error
) {
2731 console
.error( String( e
), e
);
2736 // Subscribe to error streams
2737 mw
.trackSubscribe( 'resourceloader.exception', logError
);
2738 mw
.trackSubscribe( 'resourceloader.assert', logError
);
2741 * Fired when all modules associated with the page have finished loading.
2743 * @event resourceloader_loadEnd
2747 var loading
= $.grep( mw
.loader
.getModuleNames(), function ( module
) {
2748 return mw
.loader
.getState( module
) === 'loading';
2750 // We only need a callback, not any actual module. First try a single using()
2751 // for all loading modules. If one fails, fall back to tracking each module
2752 // separately via $.when(), this is expensive.
2753 loading
= mw
.loader
.using( loading
).then( null, function () {
2754 var all
= $.map( loading
, function ( module
) {
2755 return mw
.loader
.using( module
).then( null, function () {
2756 return $.Deferred().resolve();
2759 return $.when
.apply( $, all
);
2761 loading
.then( function () {
2762 mwPerformance
.mark( 'mwLoadEnd' );
2763 mw
.hook( 'resourceloader.loadEnd' ).fire();
2767 // Attach to window and globally alias
2768 window
.mw
= window
.mediaWiki
= mw
;