2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
10 /*jshint latedef:false */
14 var mw
, StringSet
, log
,
15 hasOwn
= Object
.prototype.hasOwnProperty
,
16 slice
= Array
.prototype.slice
,
17 trackCallbacks
= $.Callbacks( 'memory' ),
22 * FNV132 hash function
24 * This function implements the 32-bit version of FNV-1.
25 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
26 * its output is base 36 rather than hex.
27 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
30 * @param {string} str String to hash
31 * @return {string} hash as an seven-character base 36 string
33 function fnv132( str
) {
34 /*jshint bitwise:false */
35 var hash
= 0x811C9DC5,
38 for ( i
= 0; i
< str
.length
; i
++ ) {
39 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
40 hash
^= str
.charCodeAt( i
);
43 hash
= ( hash
>>> 0 ).toString( 36 );
44 while ( hash
.length
< 7 ) {
51 StringSet
= window
.Set
|| ( function () {
56 function StringSet() {
59 StringSet
.prototype.add = function ( value
) {
60 this.set[ value
] = true;
62 StringSet
.prototype.has = function ( value
) {
63 return this.set.hasOwnProperty( value
);
69 * Create an object that can be read from or written to from methods that allow
70 * interaction both with single and multiple properties at once.
74 * var collection, query, results;
76 * // Create your address book
77 * collection = new mw.Map();
79 * // This data could be coming from an external source (eg. API/AJAX)
81 * 'John Doe': 'john@example.org',
82 * 'Jane Doe': 'jane@example.org',
83 * 'George van Halen': 'gvanhalen@example.org'
86 * wanted = ['John Doe', 'Jane Doe', 'Daniel Jackson'];
88 * // You can detect missing keys first
89 * if ( !collection.exists( wanted ) ) {
90 * // One or more are missing (in this case: "Daniel Jackson")
91 * mw.log( 'One or more names were not found in your address book' );
94 * // Or just let it give you what it can. Optionally fill in from a default.
95 * results = collection.get( wanted, 'nobody@example.com' );
96 * mw.log( results['Jane Doe'] ); // "jane@example.org"
97 * mw.log( results['Daniel Jackson'] ); // "nobody@example.com"
102 * @param {Object|boolean} [values] The value-baring object to be mapped. Defaults to an
104 * For backwards-compatibility with mw.config, this can also be `true` in which case values
105 * are copied to the Window object as global variables (T72470). Values are copied in
106 * one direction only. Changes to globals are not reflected in the map.
108 function Map( values
) {
109 if ( values
=== true ) {
112 // Override #set to also set the global variable
113 this.set = function ( selection
, value
) {
116 if ( $.isPlainObject( selection
) ) {
117 for ( s
in selection
) {
118 setGlobalMapValue( this, s
, selection
[ s
] );
122 if ( typeof selection
=== 'string' && arguments
.length
) {
123 setGlobalMapValue( this, selection
, value
);
132 this.values
= values
|| {};
136 * Alias property to the global object.
140 * @param {mw.Map} map
141 * @param {string} key
142 * @param {Mixed} value
144 function setGlobalMapValue( map
, key
, value
) {
145 map
.values
[ key
] = value
;
150 // Deprecation notice for mw.config globals (T58550, T72470)
151 map
=== mw
.config
&& 'Use mw.config instead.'
157 * Get the value of one or more keys.
159 * If called with no arguments, all values are returned.
161 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
162 * @param {Mixed} [fallback=null] Value for keys that don't exist.
163 * @return {Mixed|Object| null} If selection was a string, returns the value,
164 * If selection was an array, returns an object of key/values.
165 * If no selection is passed, the 'values' container is returned. (Beware that,
166 * as is the default in JavaScript, the object is returned by reference.)
168 get: function ( selection
, fallback
) {
170 // If we only do this in the `return` block, it'll fail for the
171 // call to get() from the mutli-selection block.
172 fallback
= arguments
.length
> 1 ? fallback
: null;
174 if ( $.isArray( selection
) ) {
175 selection
= slice
.call( selection
);
177 for ( i
= 0; i
< selection
.length
; i
++ ) {
178 results
[ selection
[ i
] ] = this.get( selection
[ i
], fallback
);
183 if ( typeof selection
=== 'string' ) {
184 if ( !hasOwn
.call( this.values
, selection
) ) {
187 return this.values
[ selection
];
190 if ( selection
=== undefined ) {
194 // Invalid selection key
199 * Set one or more key/value pairs.
201 * @param {string|Object} selection Key to set value for, or object mapping keys to values
202 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
203 * @return {boolean} True on success, false on failure
205 set: function ( selection
, value
) {
208 if ( $.isPlainObject( selection
) ) {
209 for ( s
in selection
) {
210 this.values
[ s
] = selection
[ s
];
214 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
215 this.values
[ selection
] = value
;
222 * Check if one or more keys exist.
224 * @param {Mixed} selection Key or array of keys to check
225 * @return {boolean} True if the key(s) exist
227 exists: function ( selection
) {
230 if ( $.isArray( selection
) ) {
231 for ( s
= 0; s
< selection
.length
; s
++ ) {
232 if ( typeof selection
[ s
] !== 'string' || !hasOwn
.call( this.values
, selection
[ s
] ) ) {
238 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
243 * Object constructor for messages.
245 * Similar to the Message class in MediaWiki PHP.
247 * Format defaults to 'text'.
253 * 'hello': 'Hello world',
254 * 'hello-user': 'Hello, $1!',
255 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
258 * obj = new mw.Message( mw.messages, 'hello' );
259 * mw.log( obj.text() );
262 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
263 * mw.log( obj.text() );
264 * // Hello, John Doe!
266 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
267 * mw.log( obj.text() );
268 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
270 * // Using mw.message shortcut
271 * obj = mw.message( 'hello-user', 'John Doe' );
272 * mw.log( obj.text() );
273 * // Hello, John Doe!
275 * // Using mw.msg shortcut
276 * str = mw.msg( 'hello-user', 'John Doe' );
278 * // Hello, John Doe!
280 * // Different formats
281 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
283 * obj.format = 'text';
284 * str = obj.toString();
289 * // Hello, John "Wiki" <3 Doe!
291 * mw.log( obj.escaped() );
292 * // Hello, John "Wiki" <3 Doe!
297 * @param {mw.Map} map Message store
298 * @param {string} key
299 * @param {Array} [parameters]
301 function Message( map
, key
, parameters
) {
302 this.format
= 'text';
305 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
309 Message
.prototype = {
311 * Get parsed contents of the message.
313 * The default parser does simple $N replacements and nothing else.
314 * This may be overridden to provide a more complex message parser.
315 * The primary override is in the mediawiki.jqueryMsg module.
317 * This function will not be called for nonexistent messages.
319 * @return {string} Parsed message
321 parser: function () {
322 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
326 * Add (does not replace) parameters for `$N` placeholder values.
328 * @param {Array} parameters
331 params: function ( parameters
) {
333 for ( i
= 0; i
< parameters
.length
; i
++ ) {
334 this.parameters
.push( parameters
[ i
] );
340 * Convert message object to its string form based on current format.
342 * @return {string} Message as a string in the current form, or `<key>` if key
345 toString: function () {
348 if ( !this.exists() ) {
349 // Use <key> as text if key does not exist
350 if ( this.format
=== 'escaped' || this.format
=== 'parse' ) {
351 // format 'escaped' and 'parse' need to have the brackets and key html escaped
352 return mw
.html
.escape( '<' + this.key
+ '>' );
354 return '<' + this.key
+ '>';
357 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
358 text
= this.parser();
361 if ( this.format
=== 'escaped' ) {
362 text
= this.parser();
363 text
= mw
.html
.escape( text
);
370 * Change format to 'parse' and convert message to string
372 * If jqueryMsg is loaded, this parses the message text from wikitext
373 * (where supported) to HTML
375 * Otherwise, it is equivalent to plain.
377 * @return {string} String form of parsed message
380 this.format
= 'parse';
381 return this.toString();
385 * Change format to 'plain' and convert message to string
387 * This substitutes parameters, but otherwise does not change the
390 * @return {string} String form of plain message
393 this.format
= 'plain';
394 return this.toString();
398 * Change format to 'text' and convert message to string
400 * If jqueryMsg is loaded, {{-transformation is done where supported
401 * (such as {{plural:}}, {{gender:}}, {{int:}}).
403 * Otherwise, it is equivalent to plain
405 * @return {string} String form of text message
408 this.format
= 'text';
409 return this.toString();
413 * Change the format to 'escaped' and convert message to string
415 * This is equivalent to using the 'text' format (see #text), then
416 * HTML-escaping the output.
418 * @return {string} String form of html escaped message
420 escaped: function () {
421 this.format
= 'escaped';
422 return this.toString();
426 * Check if a message exists
431 exists: function () {
432 return this.map
.exists( this.key
);
436 log
= ( function () {
437 // Also update the restoration of methods in mediawiki.log.js
438 // when adding or removing methods here.
439 var log = function () {},
440 console
= window
.console
;
448 * Write a message to the console's warning channel.
449 * Actions not supported by the browser console are silently ignored.
451 * @param {...string} msg Messages to output to console
453 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
454 Function
.prototype.bind
.call( console
.warn
, console
) :
458 * Write a message to the console's error channel.
460 * Most browsers provide a stacktrace by default if the argument
461 * is a caught Error object.
464 * @param {Error|...string} msg Messages to output to console
466 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
467 Function
.prototype.bind
.call( console
.error
, console
) :
471 * Create a property in a host object that, when accessed, will produce
472 * a deprecation warning in the console.
474 * @param {Object} obj Host object of deprecated property
475 * @param {string} key Name of property to create in `obj`
476 * @param {Mixed} val The value this property should return when accessed
477 * @param {string} [msg] Optional text to include in the deprecation message
479 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
481 } : function ( obj
, key
, val
, msg
) {
482 msg
= 'Use of "' + key
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
483 var logged
= new StringSet();
484 function uniqueTrace() {
485 var trace
= new Error().stack
;
486 if ( logged
.has( trace
) ) {
492 // Support: Safari 5.0
493 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
494 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
496 Object
.defineProperty( obj
, key
, {
500 if ( uniqueTrace() ) {
501 mw
.track( 'mw.deprecate', key
);
506 set: function ( newVal
) {
507 if ( uniqueTrace() ) {
508 mw
.track( 'mw.deprecate', key
);
528 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
530 * On browsers that implement the Navigation Timing API, this function will produce floating-point
531 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
532 * it will fall back to using `Date`.
534 * @return {number} Current time
537 var perf
= window
.performance
,
538 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
539 return navStart
&& typeof perf
.now
=== 'function' ?
540 function () { return navStart
+ perf
.now(); } :
541 function () { return +new Date(); };
545 * Format a string. Replace $1, $2 ... $N with positional arguments.
547 * Used by Message#parser().
550 * @param {string} formatString Format string
551 * @param {...Mixed} parameters Values for $N replacements
552 * @return {string} Formatted string
554 format: function ( formatString
) {
555 var parameters
= slice
.call( arguments
, 1 );
556 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
557 var index
= parseInt( match
, 10 ) - 1;
558 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
563 * Track an analytic event.
565 * This method provides a generic means for MediaWiki JavaScript code to capture state
566 * information for analysis. Each logged event specifies a string topic name that describes
567 * the kind of event that it is. Topic names consist of dot-separated path components,
568 * arranged from most general to most specific. Each path component should have a clear and
569 * well-defined purpose.
571 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
572 * events that match their subcription, including those that fired before the handler was
575 * @param {string} topic Topic name
576 * @param {Object} [data] Data describing the event, encoded as an object
578 track: function ( topic
, data
) {
579 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
580 trackCallbacks
.fire( trackQueue
);
584 * Register a handler for subset of analytic events, specified by topic.
586 * Handlers will be called once for each tracked event, including any events that fired before the
587 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
588 * the exact time at which the event fired, a string 'topic' property naming the event, and a
589 * 'data' property which is an object of event-specific data. The event topic and event data are
590 * also passed to the callback as the first and second arguments, respectively.
592 * @param {string} topic Handle events whose name starts with this string prefix
593 * @param {Function} callback Handler to call for each matching tracked event
594 * @param {string} callback.topic
595 * @param {Object} [callback.data]
597 trackSubscribe: function ( topic
, callback
) {
599 function handler( trackQueue
) {
601 for ( ; seen
< trackQueue
.length
; seen
++ ) {
602 event
= trackQueue
[ seen
];
603 if ( event
.topic
.indexOf( topic
) === 0 ) {
604 callback
.call( event
, event
.topic
, event
.data
);
609 trackHandlers
.push( [ handler
, callback
] );
611 trackCallbacks
.add( handler
);
615 * Stop handling events for a particular handler
617 * @param {Function} callback
619 trackUnsubscribe: function ( callback
) {
620 trackHandlers
= $.grep( trackHandlers
, function ( fns
) {
621 if ( fns
[ 1 ] === callback
) {
622 trackCallbacks
.remove( fns
[ 0 ] );
623 // Ensure the tuple is removed to avoid holding on to closures
630 // Expose Map constructor
633 // Expose Message constructor
637 * Map of configuration values.
639 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
642 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
643 * global `window` object.
645 * @property {mw.Map} config
647 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
651 * Empty object for third-party libraries, for cases where you don't
652 * want to add a new global, or the global is bad and needs containment
660 * Access container for deprecated functionality that can be moved from
661 * from their legacy location and attached to this object (e.g. a global
662 * function that is deprecated and as stop-gap can be exposed through here).
664 * This was reserved for future use but never ended up being used.
666 * @deprecated since 1.22 Let deprecated identifiers keep their original name
667 * and use mw.log#deprecate to create an access container for tracking.
673 * Store for messages.
680 * Store for templates associated with a module.
684 templates
: new Map(),
687 * Get a message object.
689 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
692 * @param {string} key Key of message to get
693 * @param {...Mixed} parameters Values for $N replacements
694 * @return {mw.Message}
696 message: function ( key
) {
697 var parameters
= slice
.call( arguments
, 1 );
698 return new Message( mw
.messages
, key
, parameters
);
702 * Get a message string using the (default) 'text' format.
704 * Shortcut for `mw.message( key, parameters... ).text()`.
707 * @param {string} key Key of message to get
708 * @param {...Mixed} parameters Values for $N replacements
712 return mw
.message
.apply( mw
.message
, arguments
).toString();
716 * No-op dummy placeholder for {@link mw.log} in debug mode.
723 * Client for ResourceLoader server end point.
725 * This client is in charge of maintaining the module registry and state
726 * machine, initiating network (batch) requests for loading modules, as
727 * well as dependency resolution and execution of source code.
729 * For more information, refer to
730 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
735 loader
: ( function () {
738 * Fired via mw.track on various resource loading errors.
740 * @event resourceloader_exception
741 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
742 * object, but in theory module code could manually throw something else, and that
743 * might also end up here.
744 * @param {string} [module] Name of the module which caused the error. Omitted if the
745 * error is not module-related or the module cannot be easily identified due to
747 * @param {string} source Source of the error. Possible values:
749 * - style: stylesheet error (only affects old IE where a special style loading method
751 * - load-callback: exception thrown by user callback
752 * - module-execute: exception thrown by module code
753 * - store-eval: could not evaluate module code cached in localStorage
754 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
755 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
756 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
760 * Fired via mw.track on resource loading error conditions.
762 * @event resourceloader_assert
763 * @param {string} source Source of the error. Possible values:
765 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
766 * bug; see <https://phabricator.wikimedia.org/T59567> for details
770 * Mapping of registered modules.
772 * See #implement and #execute for exact details on support for script, style and messages.
778 * // From mw.loader.register()
779 * 'version': '########' (hash)
780 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
781 * 'group': 'somegroup', (or) null
782 * 'source': 'local', (or) 'anotherwiki'
783 * 'skip': 'return !!window.Example', (or) null
784 * 'module': export Object
786 * // Set from execute() or mw.loader.state()
787 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
789 * // Optionally added at run-time by mw.loader.implement()
791 * 'script': closure, array of urls, or string
792 * 'style': { ... } (see #execute)
793 * 'messages': { 'key': 'value', ... }
800 * The module is known to the system but not yet required.
801 * Meta data is registered via mw.loader#register. Calls to that method are
802 * generated server-side by the startup module.
804 * The module was required through mw.loader (either directly or as dependency of
805 * another module). The client will fetch module contents from the server.
806 * The contents are then stashed in the registry via mw.loader#implement.
808 * The module has been loaded from the server and stashed via mw.loader#implement.
809 * If the module has no more dependencies in-flight, the module will be executed
810 * immediately. Otherwise execution is deferred, controlled via #handlePending.
812 * The module is being executed.
814 * The module has been successfully executed.
816 * The module (or one of its dependencies) produced an error during execution.
818 * The module was registered client-side and requested, but the server denied knowledge
819 * of the module's existence.
825 // Mapping of sources, keyed by source-id, values are strings.
830 // 'sourceId': 'http://example.org/w/load.php'
835 // For queueModuleScript()
836 handlingPendingRequests
= false,
837 pendingRequests
= [],
839 // List of modules to be loaded
843 * List of callback jobs waiting for modules to be ready.
845 * Jobs are created by #enqueue() and run by #handlePending().
847 * Typically when a job is created for a module, the job's dependencies contain
848 * both the required module and all its recursive dependencies.
853 * 'dependencies': [ module names ],
854 * 'ready': Function callback
855 * 'error': Function callback
858 * @property {Object[]} jobs
866 // For addEmbeddedCSS()
868 cssBufferTimer
= null,
869 cssCallbacks
= $.Callbacks(),
870 isIE9
= document
.documentMode
=== 9,
871 rAF
= window
.requestAnimationFrame
|| setTimeout
;
873 function getMarker() {
876 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
878 mw
.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
879 marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
886 * Create a new style element and add it to the DOM.
889 * @param {string} text CSS text
890 * @param {Node} [nextNode] The element where the style tag
891 * should be inserted before
892 * @return {HTMLElement} Reference to the created style element
894 function newStyleTag( text
, nextNode
) {
895 var s
= document
.createElement( 'style' );
897 s
.appendChild( document
.createTextNode( text
) );
898 if ( nextNode
&& nextNode
.parentNode
) {
899 nextNode
.parentNode
.insertBefore( s
, nextNode
);
901 document
.getElementsByTagName( 'head' )[ 0 ].appendChild( s
);
908 * Add a bit of CSS text to the current browser page.
910 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
911 * or create a new one based on whether the given `cssText` is safe for extension.
914 * @param {string} [cssText=cssBuffer] If called without cssText,
915 * the internal buffer will be inserted instead.
916 * @param {Function} [callback]
918 function addEmbeddedCSS( cssText
, callback
) {
921 function fireCallbacks() {
922 var oldCallbacks
= cssCallbacks
;
923 // Reset cssCallbacks variable so it's not polluted by any calls to
924 // addEmbeddedCSS() from one of the callbacks (T105973)
925 cssCallbacks
= $.Callbacks();
926 oldCallbacks
.fire().empty();
930 cssCallbacks
.add( callback
);
933 // Yield once before creating the <style> tag. This lets multiple stylesheets
934 // accumulate into one buffer, allowing us to reduce how often new stylesheets
935 // are inserted in the browser. Appending a stylesheet and waiting for the
936 // browser to repaint is fairly expensive. (T47810)
938 // Don't extend the buffer if the item needs its own stylesheet.
939 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
940 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
941 // Linebreak for somewhat distinguishable sections
942 cssBuffer
+= '\n' + cssText
;
943 if ( !cssBufferTimer
) {
944 cssBufferTimer
= rAF( function () {
945 // Wrap in anonymous function that takes no arguments
946 // Support: Firefox < 13
947 // Firefox 12 has non-standard behaviour of passing a number
948 // as first argument to a setTimeout callback.
949 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
956 // This is a scheduled flush for the buffer
958 cssBufferTimer
= null;
963 // By default, always create a new <style>. Appending text to a <style> tag is
964 // is a performance anti-pattern as it requires CSS to be reparsed (T47810).
967 // Try to re-use existing <style> tags due to the IE stylesheet limit (T33676).
969 $style
= $( getMarker() ).prev();
970 // Verify that the element before the marker actually is a <style> tag created
971 // by mw.loader (not some other style tag, or e.g. a <meta> tag).
972 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) ) {
973 styleEl
= $style
[ 0 ];
974 styleEl
.appendChild( document
.createTextNode( cssText
) );
978 // Else: No existing tag to reuse. Continue below and create the first one.
981 $style
= $( newStyleTag( cssText
, getMarker() ) );
984 $style
.data( 'ResourceLoaderDynamicStyleTag', true );
992 * @param {Array} modules List of module names
993 * @return {string} Hash of concatenated version hashes.
995 function getCombinedVersion( modules
) {
996 var hashes
= $.map( modules
, function ( module
) {
997 return registry
[ module
].version
;
999 return fnv132( hashes
.join( '' ) );
1003 * Determine whether all dependencies are in state 'ready', which means we may
1004 * execute the module or job now.
1007 * @param {Array} modules Names of modules to be checked
1008 * @return {boolean} True if all modules are in state 'ready', false otherwise
1010 function allReady( modules
) {
1012 for ( i
= 0; i
< modules
.length
; i
++ ) {
1013 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
1021 * Determine whether all dependencies are in state 'ready', which means we may
1022 * execute the module or job now.
1025 * @param {Array} modules Names of modules to be checked
1026 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1028 function anyFailed( modules
) {
1030 for ( i
= 0; i
< modules
.length
; i
++ ) {
1031 state
= mw
.loader
.getState( modules
[ i
] );
1032 if ( state
=== 'error' || state
=== 'missing' ) {
1040 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1041 * pending jobs and modules that depend upon this module. If the given module failed,
1042 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1043 * all jobs/modules now having their dependencies satisfied.
1045 * Jobs that depend on a failed module, will have their error callback ran (if any).
1048 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1050 function handlePending( module
) {
1051 var j
, job
, hasErrors
, m
, stateChange
;
1053 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1054 // If the current module failed, mark all dependent modules also as failed.
1055 // Iterate until steady-state to propagate the error state upwards in the
1058 stateChange
= false;
1059 for ( m
in registry
) {
1060 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1061 if ( anyFailed( registry
[ m
].dependencies
) ) {
1062 registry
[ m
].state
= 'error';
1067 } while ( stateChange
);
1070 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1071 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1072 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1073 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1074 // All dependencies satisfied, or some have errors
1076 jobs
.splice( j
, 1 );
1080 if ( typeof job
.error
=== 'function' ) {
1081 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1084 if ( typeof job
.ready
=== 'function' ) {
1089 // A user-defined callback raised an exception.
1090 // Swallow it to protect our state machine!
1091 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1096 if ( registry
[ module
].state
=== 'ready' ) {
1097 // The current module became 'ready'. Set it in the module store, and recursively execute all
1098 // dependent modules that are loaded and now have all dependencies satisfied.
1099 mw
.loader
.store
.set( module
, registry
[ module
] );
1100 for ( m
in registry
) {
1101 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1109 * Resolve dependencies and detect circular references.
1112 * @param {string} module Name of the top-level module whose dependencies shall be
1113 * resolved and sorted.
1114 * @param {Array} resolved Returns a topological sort of the given module and its
1115 * dependencies, such that later modules depend on earlier modules. The array
1116 * contains the module names. If the array contains already some module names,
1117 * this function appends its result to the pre-existing array.
1118 * @param {StringSet} [unresolved] Used to track the current dependency
1119 * chain, and to report loops in the dependency graph.
1120 * @throws {Error} If any unregistered module or a dependency loop is encountered
1122 function sortDependencies( module
, resolved
, unresolved
) {
1125 if ( !hasOwn
.call( registry
, module
) ) {
1126 throw new Error( 'Unknown dependency: ' + module
);
1129 if ( registry
[ module
].skip
!== null ) {
1130 /*jshint evil:true */
1131 skip
= new Function( registry
[ module
].skip
);
1132 registry
[ module
].skip
= null;
1134 registry
[ module
].skipped
= true;
1135 registry
[ module
].dependencies
= [];
1136 registry
[ module
].state
= 'ready';
1137 handlePending( module
);
1142 // Resolves dynamic loader function and replaces it with its own results
1143 if ( typeof registry
[ module
].dependencies
=== 'function' ) {
1144 registry
[ module
].dependencies
= registry
[ module
].dependencies();
1145 // Ensures the module's dependencies are always in an array
1146 if ( typeof registry
[ module
].dependencies
!== 'object' ) {
1147 registry
[ module
].dependencies
= [ registry
[ module
].dependencies
];
1150 if ( $.inArray( module
, resolved
) !== -1 ) {
1151 // Module already resolved; nothing to do
1154 // Create unresolved if not passed in
1155 if ( !unresolved
) {
1156 unresolved
= new StringSet();
1158 // Tracks down dependencies
1159 deps
= registry
[ module
].dependencies
;
1160 for ( i
= 0; i
< deps
.length
; i
++ ) {
1161 if ( $.inArray( deps
[ i
], resolved
) === -1 ) {
1162 if ( unresolved
.has( deps
[ i
] ) ) {
1163 throw new Error( mw
.format(
1164 'Circular reference detected: $1 -> $2',
1170 unresolved
.add( module
);
1171 sortDependencies( deps
[ i
], resolved
, unresolved
);
1174 resolved
.push( module
);
1178 * Get names of module that a module depends on, in their proper dependency order.
1181 * @param {string[]} modules Array of string module names
1182 * @return {Array} List of dependencies, including 'module'.
1184 function resolve( modules
) {
1186 $.each( modules
, function ( idx
, module
) {
1187 sortDependencies( module
, resolved
);
1193 * Load and execute a script.
1196 * @param {string} src URL to script, will be used as the src attribute in the script tag
1197 * @return {jQuery.Promise}
1199 function addScript( src
) {
1203 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1204 // XHR for a same domain request instead of <script>, which changes the request
1205 // headers (potentially missing a cache hit), and reduces caching in general
1206 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1207 // text, so we'd need to $.globalEval, which then messes up line numbers.
1214 * Queue the loading and execution of a script for a particular module.
1217 * @param {string} src URL of the script
1218 * @param {string} [moduleName] Name of currently executing module
1219 * @return {jQuery.Promise}
1221 function queueModuleScript( src
, moduleName
) {
1222 var r
= $.Deferred();
1224 pendingRequests
.push( function () {
1225 if ( moduleName
&& hasOwn
.call( registry
, moduleName
) ) {
1226 // Emulate runScript() part of execute()
1227 window
.require
= mw
.loader
.require
;
1228 window
.module
= registry
[ moduleName
].module
;
1230 addScript( src
).always( function () {
1231 // 'module.exports' should not persist after the file is executed to
1232 // avoid leakage to unrelated code. 'require' should be kept, however,
1233 // as asynchronous access to 'require' is allowed and expected. (T144879)
1234 delete window
.module
;
1237 // Start the next one (if any)
1238 if ( pendingRequests
[ 0 ] ) {
1239 pendingRequests
.shift()();
1241 handlingPendingRequests
= false;
1245 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1246 handlingPendingRequests
= true;
1247 pendingRequests
.shift()();
1253 * Utility function for execute()
1257 function addLink( media
, url
) {
1258 var el
= document
.createElement( 'link' );
1260 el
.rel
= 'stylesheet';
1261 if ( media
&& media
!== 'all' ) {
1264 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1265 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1268 $( getMarker() ).before( 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
, legacyWait
, implicitDependencies
,
1292 // Expand to include dependencies since we have to exclude both legacy modules
1293 // and their dependencies from the legacyWait (to prevent a circular dependency).
1294 legacyModules
= resolve( mw
.config
.get( 'wgResourceLoaderLegacyModules', [] ) );
1296 script
= registry
[ module
].script
;
1297 markModuleReady = function () {
1298 registry
[ module
].state
= 'ready';
1299 handlePending( module
);
1301 nestedAddScript = function ( arr
, callback
, i
) {
1302 // Recursively call queueModuleScript() in its own callback
1303 // for each element of arr.
1304 if ( i
>= arr
.length
) {
1305 // We're at the end of the array
1310 queueModuleScript( arr
[ i
], module
).always( function () {
1311 nestedAddScript( arr
, callback
, i
+ 1 );
1315 implicitDependencies
= ( $.inArray( module
, legacyModules
) !== -1 )
1319 if ( module
=== 'user' ) {
1320 // Implicit dependency on the site module. Not real dependency because
1321 // it should run after 'site' regardless of whether it succeeds or fails.
1322 implicitDependencies
.push( 'site' );
1325 legacyWait
= implicitDependencies
.length
1326 ? mw
.loader
.using( implicitDependencies
)
1327 : $.Deferred().resolve();
1329 legacyWait
.always( function () {
1331 if ( $.isArray( script
) ) {
1332 nestedAddScript( script
, markModuleReady
, 0 );
1333 } else if ( typeof script
=== 'function' ) {
1334 // Pass jQuery twice so that the signature of the closure which wraps
1335 // the script can bind both '$' and 'jQuery'.
1336 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1339 } else if ( typeof script
=== 'string' ) {
1340 // Site and user modules are legacy scripts that run in the global scope.
1341 // This is transported as a string instead of a function to avoid needing
1342 // to use string manipulation to undo the function wrapper.
1343 $.globalEval( script
);
1347 // Module without script
1351 // Use mw.track instead of mw.log because these errors are common in production mode
1352 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1353 registry
[ module
].state
= 'error';
1354 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1355 handlePending( module
);
1360 // Add localizations to message system
1361 if ( registry
[ module
].messages
) {
1362 mw
.messages
.set( registry
[ module
].messages
);
1365 // Initialise templates
1366 if ( registry
[ module
].templates
) {
1367 mw
.templates
.set( module
, registry
[ module
].templates
);
1370 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1373 checkCssHandles = function () {
1374 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1375 // one of the cssHandles is fired while we're still creating more handles.
1376 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1378 runScript
= undefined; // Revoke
1381 cssHandle = function () {
1382 var check
= checkCssHandles
;
1384 return function () {
1388 check
= undefined; // Revoke
1394 // Process styles (see also mw.loader.implement)
1395 // * back-compat: { <media>: css }
1396 // * back-compat: { <media>: [url, ..] }
1397 // * { "css": [css, ..] }
1398 // * { "url": { <media>: [url, ..] } }
1399 if ( registry
[ module
].style
) {
1400 for ( key
in registry
[ module
].style
) {
1401 value
= registry
[ module
].style
[ key
];
1404 if ( key
!== 'url' && key
!== 'css' ) {
1405 // Backwards compatibility, key is a media-type
1406 if ( typeof value
=== 'string' ) {
1407 // back-compat: { <media>: css }
1408 // Ignore 'media' because it isn't supported (nor was it used).
1409 // Strings are pre-wrapped in "@media". The media-type was just ""
1410 // (because it had to be set to something).
1411 // This is one of the reasons why this format is no longer used.
1412 addEmbeddedCSS( value
, cssHandle() );
1414 // back-compat: { <media>: [url, ..] }
1420 // Array of css strings in key 'css',
1421 // or back-compat array of urls from media-type
1422 if ( $.isArray( value
) ) {
1423 for ( i
= 0; i
< value
.length
; i
++ ) {
1424 if ( key
=== 'bc-url' ) {
1425 // back-compat: { <media>: [url, ..] }
1426 addLink( media
, value
[ i
] );
1427 } else if ( key
=== 'css' ) {
1428 // { "css": [css, ..] }
1429 addEmbeddedCSS( value
[ i
], cssHandle() );
1432 // Not an array, but a regular object
1433 // Array of urls inside media-type key
1434 } else if ( typeof value
=== 'object' ) {
1435 // { "url": { <media>: [url, ..] } }
1436 for ( media
in value
) {
1437 urls
= value
[ media
];
1438 for ( i
= 0; i
< urls
.length
; i
++ ) {
1439 addLink( media
, urls
[ i
] );
1447 cssHandlesRegistered
= true;
1452 * Add one or more modules to the module load queue.
1457 * @param {string|string[]} dependencies Module name or array of string module names
1458 * @param {Function} [ready] Callback to execute when all dependencies are ready
1459 * @param {Function} [error] Callback to execute when any dependency fails
1461 function enqueue( dependencies
, ready
, error
) {
1462 // Allow calling by single module name
1463 if ( typeof dependencies
=== 'string' ) {
1464 dependencies
= [ dependencies
];
1467 // Add ready and error callbacks if they were given
1468 if ( ready
!== undefined || error
!== undefined ) {
1470 // Narrow down the list to modules that are worth waiting for
1471 dependencies
: $.grep( dependencies
, function ( module
) {
1472 var state
= mw
.loader
.getState( module
);
1473 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1480 $.each( dependencies
, function ( idx
, module
) {
1481 var state
= mw
.loader
.getState( module
);
1482 // Only queue modules that are still in the initial 'registered' state
1483 // (not ones already loading, ready or error).
1484 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1485 // Private modules must be embedded in the page. Don't bother queuing
1486 // these as the server will deny them anyway (T101806).
1487 if ( registry
[ module
].group
=== 'private' ) {
1488 registry
[ module
].state
= 'error';
1489 handlePending( module
);
1492 queue
.push( module
);
1499 function sortQuery( o
) {
1505 if ( hasOwn
.call( o
, key
) ) {
1510 for ( key
= 0; key
< a
.length
; key
++ ) {
1511 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1517 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1518 * to a query string of the form foo.bar,baz|bar.baz,quux
1522 function buildModulesString( moduleMap
) {
1526 for ( prefix
in moduleMap
) {
1527 p
= prefix
=== '' ? '' : prefix
+ '.';
1528 arr
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1530 return arr
.join( '|' );
1534 * Make a network request to load modules from the server.
1537 * @param {Object} moduleMap Module map, see #buildModulesString
1538 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1539 * @param {string} sourceLoadScript URL of load.php
1541 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
1542 var query
= $.extend(
1543 { modules
: buildModulesString( moduleMap
) },
1546 query
= sortQuery( query
);
1547 addScript( sourceLoadScript
+ '?' + $.param( query
) );
1551 * Resolve indexed dependencies.
1553 * ResourceLoader uses an optimization to save space which replaces module names in
1554 * dependency lists with the index of that module within the array of module
1555 * registration data if it exists. The benefit is a significant reduction in the data
1556 * size of the startup module. This function changes those dependency lists back to
1557 * arrays of strings.
1560 * @param {Array} modules Modules array
1562 function resolveIndexedDependencies( modules
) {
1564 function resolveIndex( dep
) {
1565 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1567 for ( i
= 0; i
< modules
.length
; i
++ ) {
1568 deps
= modules
[ i
][ 2 ];
1570 for ( j
= 0; j
< deps
.length
; j
++ ) {
1571 deps
[ j
] = resolveIndex( deps
[ j
] );
1578 * Create network requests for a batch of modules.
1580 * This is an internal method for #work(). This must not be called directly
1581 * unless the modules are already registered, and no request is in progress,
1582 * and the module state has already been set to `loading`.
1585 * @param {string[]} batch
1587 function batchRequest( batch
) {
1588 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1589 source
, group
, i
, modules
, sourceLoadScript
,
1590 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1591 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1593 if ( !batch
.length
) {
1597 // Always order modules alphabetically to help reduce cache
1598 // misses for otherwise identical content.
1601 // Build a list of query parameters common to all requests
1603 skin
: mw
.config
.get( 'skin' ),
1604 lang
: mw
.config
.get( 'wgUserLanguage' ),
1605 debug
: mw
.config
.get( 'debug' )
1607 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1609 // Split module list by source and by group.
1611 for ( b
= 0; b
< batch
.length
; b
++ ) {
1612 bSource
= registry
[ batch
[ b
] ].source
;
1613 bGroup
= registry
[ batch
[ b
] ].group
;
1614 if ( !hasOwn
.call( splits
, bSource
) ) {
1615 splits
[ bSource
] = {};
1617 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1618 splits
[ bSource
][ bGroup
] = [];
1620 bSourceGroup
= splits
[ bSource
][ bGroup
];
1621 bSourceGroup
.push( batch
[ b
] );
1624 for ( source
in splits
) {
1626 sourceLoadScript
= sources
[ source
];
1628 for ( group
in splits
[ source
] ) {
1630 // Cache access to currently selected list of
1631 // modules for this group from this source.
1632 modules
= splits
[ source
][ group
];
1634 currReqBase
= $.extend( {
1635 version
: getCombinedVersion( modules
)
1637 // For user modules append a user name to the query string.
1638 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1639 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1641 currReqBaseLength
= $.param( currReqBase
).length
;
1642 // We may need to split up the request to honor the query string length limit,
1643 // so build it piece by piece.
1644 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1646 moduleMap
= {}; // { prefix: [ suffixes ] }
1648 for ( i
= 0; i
< modules
.length
; i
++ ) {
1649 // Determine how many bytes this module would add to the query string
1650 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1652 // If lastDotIndex is -1, substr() returns an empty string
1653 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1654 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1656 bytesAdded
= hasOwn
.call( moduleMap
, prefix
)
1657 ? suffix
.length
+ 3 // '%2C'.length == 3
1658 : modules
[ i
].length
+ 3; // '%7C'.length == 3
1660 // If the url would become too long, create a new one,
1661 // but don't create empty requests
1662 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1663 // This url would become too long, create a new one, and start the old one
1664 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1666 l
= currReqBaseLength
+ 9;
1667 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1669 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1670 moduleMap
[ prefix
] = [];
1672 moduleMap
[ prefix
].push( suffix
);
1675 // If there's anything left in moduleMap, request that too
1676 if ( !$.isEmptyObject( moduleMap
) ) {
1677 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1685 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1686 * form of calls to mw.loader#implement().
1687 * @param {Function} cb Callback in case of failure
1688 * @param {Error} cb.err
1690 function asyncEval( implementations
, cb
) {
1691 if ( !implementations
.length
) {
1694 mw
.requestIdleCallback( function () {
1696 $.globalEval( implementations
.join( ';' ) );
1704 * Make a versioned key for a specific module.
1707 * @param {string} module Module name
1708 * @return {string|null} Module key in format '`[name]@[version]`',
1709 * or null if the module does not exist
1711 function getModuleKey( module
) {
1712 return hasOwn
.call( registry
, module
) ?
1713 ( module
+ '@' + registry
[ module
].version
) : null;
1718 * @param {string} key Module name or '`[name]@[version]`'
1721 function splitModuleKey( key
) {
1722 var index
= key
.indexOf( '@' );
1723 if ( index
=== -1 ) {
1724 return { name
: key
};
1727 name
: key
.slice( 0, index
),
1728 version
: key
.slice( index
+ 1 )
1732 /* Public Members */
1735 * The module registry is exposed as an aid for debugging and inspecting page
1736 * state; it is not a public interface for modifying the registry.
1742 moduleRegistry
: registry
,
1745 * @inheritdoc #newStyleTag
1748 addStyleTag
: newStyleTag
,
1751 * Start loading of all queued module dependencies.
1756 var q
, batch
, implementations
, sourceModules
;
1760 // Appends a list of modules from the queue to the batch
1761 for ( q
= 0; q
< queue
.length
; q
++ ) {
1762 // Only load modules which are registered
1763 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1764 // Prevent duplicate entries
1765 if ( $.inArray( queue
[ q
], batch
) === -1 ) {
1766 batch
.push( queue
[ q
] );
1767 // Mark registered modules as loading
1768 registry
[ queue
[ q
] ].state
= 'loading';
1773 // Now that the queue has been processed into a batch, clear the queue.
1774 // This MUST happen before we initiate any eval or network request. Otherwise,
1775 // it is possible for a cached script to instantly trigger the same work queue
1776 // again; all before we've cleared it causing each request to include modules
1777 // which are already loaded.
1780 if ( !batch
.length
) {
1784 mw
.loader
.store
.init();
1785 if ( mw
.loader
.store
.enabled
) {
1786 implementations
= [];
1788 batch
= $.grep( batch
, function ( module
) {
1789 var implementation
= mw
.loader
.store
.get( module
);
1790 if ( implementation
) {
1791 implementations
.push( implementation
);
1792 sourceModules
.push( module
);
1797 asyncEval( implementations
, function ( err
) {
1798 // Not good, the cached mw.loader.implement calls failed! This should
1799 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1800 // Depending on how corrupt the string is, it is likely that some
1801 // modules' implement() succeeded while the ones after the error will
1802 // never run and leave their modules in the 'loading' state forever.
1804 // Since this is an error not caused by an individual module but by
1805 // something that infected the implement call itself, don't take any
1806 // risks and clear everything in this cache.
1807 mw
.loader
.store
.clear();
1809 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1810 // Re-add the failed ones that are still pending back to the batch
1811 var failed
= $.grep( sourceModules
, function ( module
) {
1812 return registry
[ module
].state
=== 'loading';
1814 batchRequest( failed
);
1818 batchRequest( batch
);
1822 * Register a source.
1824 * The #work() method will use this information to split up requests by source.
1826 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1828 * @param {string|Object} id Source ID, or object mapping ids to load urls
1829 * @param {string} loadUrl Url to a load.php end point
1830 * @throws {Error} If source id is already registered
1832 addSource: function ( id
, loadUrl
) {
1834 // Allow multiple additions
1835 if ( typeof id
=== 'object' ) {
1836 for ( source
in id
) {
1837 mw
.loader
.addSource( source
, id
[ source
] );
1842 if ( hasOwn
.call( sources
, id
) ) {
1843 throw new Error( 'source already registered: ' + id
);
1846 sources
[ id
] = loadUrl
;
1850 * Register a module, letting the system know about it and its properties.
1852 * The startup modules contain calls to this method.
1854 * When using multiple module registration by passing an array, dependencies that
1855 * are specified as references to modules within the array will be resolved before
1856 * the modules are registered.
1858 * @param {string|Array} module Module name or array of arrays, each containing
1859 * a list of arguments compatible with this method
1860 * @param {string|number} version Module version hash (falls backs to empty string)
1861 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1862 * @param {string|Array|Function} dependencies One string or array of strings of module
1863 * names on which this module depends, or a function that returns that array.
1864 * @param {string} [group=null] Group which the module is in
1865 * @param {string} [source='local'] Name of the source
1866 * @param {string} [skip=null] Script body of the skip function
1868 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1870 // Allow multiple registration
1871 if ( typeof module
=== 'object' ) {
1872 resolveIndexedDependencies( module
);
1873 for ( i
= 0; i
< module
.length
; i
++ ) {
1874 // module is an array of module names
1875 if ( typeof module
[ i
] === 'string' ) {
1876 mw
.loader
.register( module
[ i
] );
1877 // module is an array of arrays
1878 } else if ( typeof module
[ i
] === 'object' ) {
1879 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1884 if ( hasOwn
.call( registry
, module
) ) {
1885 throw new Error( 'module already registered: ' + module
);
1887 if ( typeof dependencies
=== 'string' ) {
1888 // A single module name
1889 deps
= [ dependencies
];
1890 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
1891 // Array of module names or a function that returns an array
1892 deps
= dependencies
;
1894 // List the module as registered
1895 registry
[ module
] = {
1896 // Exposed to execute() for mw.loader.implement() closures.
1897 // Import happens via require().
1901 version
: version
!== undefined ? String( version
) : '',
1902 dependencies
: deps
|| [],
1903 group
: typeof group
=== 'string' ? group
: null,
1904 source
: typeof source
=== 'string' ? source
: 'local',
1905 state
: 'registered',
1906 skip
: typeof skip
=== 'string' ? skip
: null
1911 * Implement a module given the components that make up the module.
1913 * When #load() or #using() requests one or more modules, the server
1914 * response contain calls to this function.
1916 * @param {string} module Name of module and current module version. Formatted
1917 * as '`[name]@[version]`". This version should match the requested version
1918 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1919 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1920 * @param {Function|Array|string} [script] Function with module code, list of URLs
1921 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1922 * @param {Object} [style] Should follow one of the following patterns:
1924 * { "css": [css, ..] }
1925 * { "url": { <media>: [url, ..] } }
1927 * And for backwards compatibility (needs to be supported forever due to caching):
1930 * { <media>: [url, ..] }
1932 * The reason css strings are not concatenated anymore is bug 31676. We now check
1933 * whether it's safe to extend the stylesheet.
1936 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1937 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1939 implement: function ( module
, script
, style
, messages
, templates
) {
1940 var split
= splitModuleKey( module
),
1942 version
= split
.version
;
1943 // Automatically register module
1944 if ( !hasOwn
.call( registry
, name
) ) {
1945 mw
.loader
.register( name
);
1947 // Check for duplicate implementation
1948 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1949 throw new Error( 'module already implemented: ' + name
);
1952 // Without this reset, if there is a version mismatch between the
1953 // requested and received module version, then mw.loader.store would
1954 // cache the response under the requested key. Thus poisoning the cache
1955 // indefinitely with a stale value. (T117587)
1956 registry
[ name
].version
= version
;
1958 // Attach components
1959 registry
[ name
].script
= script
|| null;
1960 registry
[ name
].style
= style
|| null;
1961 registry
[ name
].messages
= messages
|| null;
1962 registry
[ name
].templates
= templates
|| null;
1963 // The module may already have been marked as erroneous
1964 if ( $.inArray( registry
[ name
].state
, [ 'error', 'missing' ] ) === -1 ) {
1965 registry
[ name
].state
= 'loaded';
1966 if ( allReady( registry
[ name
].dependencies
) ) {
1973 * Execute a function as soon as one or more required modules are ready.
1975 * Example of inline dependency on OOjs:
1977 * mw.loader.using( 'oojs', function () {
1978 * OO.compare( [ 1 ], [ 1 ] );
1981 * Since MediaWiki 1.23 this also returns a promise.
1983 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1985 * @param {string|Array} dependencies Module name or array of modules names the
1986 * callback depends on to be ready before executing
1987 * @param {Function} [ready] Callback to execute when all dependencies are ready
1988 * @param {Function} [error] Callback to execute if one or more dependencies failed
1989 * @return {jQuery.Promise} With a `require` function
1991 using: function ( dependencies
, ready
, error
) {
1992 var deferred
= $.Deferred();
1994 // Allow calling with a single dependency as a string
1995 if ( typeof dependencies
=== 'string' ) {
1996 dependencies
= [ dependencies
];
2000 deferred
.done( ready
);
2003 deferred
.fail( error
);
2006 // Resolve entire dependency map
2007 dependencies
= resolve( dependencies
);
2008 if ( allReady( dependencies
) ) {
2009 // Run ready immediately
2010 deferred
.resolve( mw
.loader
.require
);
2011 } else if ( anyFailed( dependencies
) ) {
2012 // Execute error immediately if any dependencies have errors
2014 new Error( 'One or more dependencies failed to load' ),
2018 // Not all dependencies are ready, add to the load queue
2019 enqueue( dependencies
, function () {
2020 deferred
.resolve( mw
.loader
.require
);
2021 }, deferred
.reject
);
2024 return deferred
.promise();
2028 * Load an external script or one or more modules.
2030 * @param {string|Array} modules Either the name of a module, array of modules,
2031 * or a URL of an external script or style
2032 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2033 * external script or style; acceptable values are "text/css" and
2034 * "text/javascript"; if no type is provided, text/javascript is assumed.
2036 load: function ( modules
, type
) {
2039 // Allow calling with a url or single dependency as a string
2040 if ( typeof modules
=== 'string' ) {
2041 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2042 if ( /^(https?:)?\/?\//.test( modules
) ) {
2043 if ( type
=== 'text/css' ) {
2045 // Use properties instead of attributes as IE throws security
2046 // warnings when inserting a <link> tag with a protocol-relative
2047 // URL set though attributes - when on HTTPS. See bug 41331.
2048 l
= document
.createElement( 'link' );
2049 l
.rel
= 'stylesheet';
2051 $( 'head' ).append( l
);
2054 if ( type
=== 'text/javascript' || type
=== undefined ) {
2055 addScript( modules
);
2059 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2061 // Called with single module
2062 modules
= [ modules
];
2065 // Filter out undefined modules, otherwise resolve() will throw
2066 // an exception for trying to load an undefined module.
2067 // Undefined modules are acceptable here in load(), because load() takes
2068 // an array of unrelated modules, whereas the modules passed to
2069 // using() are related and must all be loaded.
2070 filtered
= $.grep( modules
, function ( module
) {
2071 var state
= mw
.loader
.getState( module
);
2072 return state
!== null && state
!== 'error' && state
!== 'missing';
2075 if ( filtered
.length
=== 0 ) {
2078 // Resolve entire dependency map
2079 filtered
= resolve( filtered
);
2080 // If all modules are ready, or if any modules have errors, nothing to be done.
2081 if ( allReady( filtered
) || anyFailed( filtered
) ) {
2084 // Some modules are not yet ready, add to module load queue.
2085 enqueue( filtered
, undefined, undefined );
2089 * Change the state of one or more modules.
2091 * @param {string|Object} module Module name or object of module name/state pairs
2092 * @param {string} state State name
2094 state: function ( module
, state
) {
2097 if ( typeof module
=== 'object' ) {
2098 for ( m
in module
) {
2099 mw
.loader
.state( m
, module
[ m
] );
2103 if ( !hasOwn
.call( registry
, module
) ) {
2104 mw
.loader
.register( module
);
2106 registry
[ module
].state
= state
;
2107 if ( $.inArray( state
, [ 'ready', 'error', 'missing' ] ) !== -1 ) {
2108 // Make sure pending modules depending on this one get executed if their
2109 // dependencies are now fulfilled!
2110 handlePending( module
);
2115 * Get the version of a module.
2117 * @param {string} module Name of module
2118 * @return {string|null} The version, or null if the module (or its version) is not
2121 getVersion: function ( module
) {
2122 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].version
=== undefined ) {
2125 return registry
[ module
].version
;
2129 * Get the state of a module.
2131 * @param {string} module Name of module
2132 * @return {string|null} The state, or null if the module (or its state) is not
2135 getState: function ( module
) {
2136 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].state
=== undefined ) {
2139 return registry
[ module
].state
;
2143 * Get the names of all registered modules.
2147 getModuleNames: function () {
2148 return $.map( registry
, function ( i
, key
) {
2154 * Get the exported value of a module.
2156 * Modules may provide this via their local `module.exports`.
2161 require: function ( moduleName
) {
2162 var state
= mw
.loader
.getState( moduleName
);
2164 // Only ready modules can be required
2165 if ( state
!== 'ready' ) {
2166 // Module may've forgotten to declare a dependency
2167 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2170 return registry
[ moduleName
].module
.exports
;
2174 * @inheritdoc mw.inspect#runReports
2177 inspect: function () {
2178 var args
= slice
.call( arguments
);
2179 mw
.loader
.using( 'mediawiki.inspect', function () {
2180 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2185 * On browsers that implement the localStorage API, the module store serves as a
2186 * smart complement to the browser cache. Unlike the browser cache, the module store
2187 * can slice a concatenated response from ResourceLoader into its constituent
2188 * modules and cache each of them separately, using each module's versioning scheme
2189 * to determine when the cache should be invalidated.
2192 * @class mw.loader.store
2195 // Whether the store is in use on this page.
2198 MODULE_SIZE_MAX
: 100 * 1000,
2200 // The contents of the store, mapping '[name]@[version]' keys
2201 // to module implementations.
2205 stats
: { hits
: 0, misses
: 0, expired
: 0 },
2208 * Construct a JSON-serializable object representing the content of the store.
2210 * @return {Object} Module store contents.
2212 toJSON: function () {
2213 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2217 * Get the localStorage key for the entire module store. The key references
2218 * $wgDBname to prevent clashes between wikis which share a common host.
2220 * @return {string} localStorage item key
2222 getStoreKey: function () {
2223 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2227 * Get a key on which to vary the module cache.
2229 * @return {string} String of concatenated vary conditions.
2231 getVary: function () {
2233 mw
.config
.get( 'skin' ),
2234 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2235 mw
.config
.get( 'wgUserLanguage' )
2240 * Initialize the store.
2242 * Retrieves store from localStorage and (if successfully retrieved) decoding
2243 * the stored JSON value to a plain object.
2245 * The try / catch block is used for JSON & localStorage feature detection.
2246 * See the in-line documentation for Modernizr's localStorage feature detection
2247 * code for a full account of why we need a try / catch:
2248 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2253 if ( mw
.loader
.store
.enabled
!== null ) {
2259 // Disabled because localStorage quotas are tight and (in Firefox's case)
2260 // shared by multiple origins.
2261 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2262 /Firefox|Opera/.test( navigator
.userAgent
) ||
2264 // Disabled by configuration.
2265 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2267 // Clear any previous store to free up space. (T66721)
2268 mw
.loader
.store
.clear();
2269 mw
.loader
.store
.enabled
= false;
2272 if ( mw
.config
.get( 'debug' ) ) {
2273 // Disable module store in debug mode
2274 mw
.loader
.store
.enabled
= false;
2279 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2280 // If we get here, localStorage is available; mark enabled
2281 mw
.loader
.store
.enabled
= true;
2282 data
= JSON
.parse( raw
);
2283 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2284 mw
.loader
.store
.items
= data
.items
;
2288 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2291 if ( raw
=== undefined ) {
2292 // localStorage failed; disable store
2293 mw
.loader
.store
.enabled
= false;
2295 mw
.loader
.store
.update();
2300 * Retrieve a module from the store and update cache hit stats.
2302 * @param {string} module Module name
2303 * @return {string|boolean} Module implementation or false if unavailable
2305 get: function ( module
) {
2308 if ( !mw
.loader
.store
.enabled
) {
2312 key
= getModuleKey( module
);
2313 if ( key
in mw
.loader
.store
.items
) {
2314 mw
.loader
.store
.stats
.hits
++;
2315 return mw
.loader
.store
.items
[ key
];
2317 mw
.loader
.store
.stats
.misses
++;
2322 * Stringify a module and queue it for storage.
2324 * @param {string} module Module name
2325 * @param {Object} descriptor The module's descriptor as set in the registry
2327 set: function ( module
, descriptor
) {
2330 if ( !mw
.loader
.store
.enabled
) {
2334 key
= getModuleKey( module
);
2337 // Already stored a copy of this exact version
2338 key
in mw
.loader
.store
.items
||
2339 // Module failed to load
2340 descriptor
.state
!== 'ready' ||
2341 // Unversioned, private, or site-/user-specific
2342 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user' ] ) !== -1 ) ||
2343 // Partial descriptor
2344 // (e.g. skipped module, or style module with state=ready)
2345 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2346 descriptor
.messages
, descriptor
.templates
] ) !== -1
2354 JSON
.stringify( key
),
2355 typeof descriptor
.script
=== 'function' ?
2356 String( descriptor
.script
) :
2357 JSON
.stringify( descriptor
.script
),
2358 JSON
.stringify( descriptor
.style
),
2359 JSON
.stringify( descriptor
.messages
),
2360 JSON
.stringify( descriptor
.templates
)
2362 // Attempted workaround for a possible Opera bug (bug T59567).
2363 // This regex should never match under sane conditions.
2364 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2365 args
[ 1 ] = 'function' + args
[ 1 ];
2366 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2369 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2373 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2374 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2377 mw
.loader
.store
.items
[ key
] = src
;
2378 mw
.loader
.store
.update();
2382 * Iterate through the module store, removing any item that does not correspond
2383 * (in name and version) to an item in the module registry.
2385 prune: function () {
2388 if ( !mw
.loader
.store
.enabled
) {
2392 for ( key
in mw
.loader
.store
.items
) {
2393 module
= key
.slice( 0, key
.indexOf( '@' ) );
2394 if ( getModuleKey( module
) !== key
) {
2395 mw
.loader
.store
.stats
.expired
++;
2396 delete mw
.loader
.store
.items
[ key
];
2397 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2398 // This value predates the enforcement of a size limit on cached modules.
2399 delete mw
.loader
.store
.items
[ key
];
2405 * Clear the entire module store right now.
2407 clear: function () {
2408 mw
.loader
.store
.items
= {};
2410 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2411 } catch ( ignored
) {}
2415 * Sync in-memory store back to localStorage.
2417 * This function debounces updates. When called with a flush already pending,
2418 * the call is coalesced into the pending update. The call to
2419 * localStorage.setItem will be naturally deferred until the page is quiescent.
2421 * Because localStorage is shared by all pages from the same origin, if multiple
2422 * pages are loaded with different module sets, the possibility exists that
2423 * modules saved by one page will be clobbered by another. But the impact would
2424 * be minor and the problem would be corrected by subsequent page views.
2428 update
: ( function () {
2429 var hasPendingWrite
= false;
2431 function flushWrites() {
2433 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2437 mw
.loader
.store
.prune();
2438 key
= mw
.loader
.store
.getStoreKey();
2440 // Replacing the content of the module store might fail if the new
2441 // contents would exceed the browser's localStorage size limit. To
2442 // avoid clogging the browser with stale data, always remove the old
2443 // value before attempting to set the new one.
2444 localStorage
.removeItem( key
);
2445 data
= JSON
.stringify( mw
.loader
.store
);
2446 localStorage
.setItem( key
, data
);
2448 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2451 hasPendingWrite
= false;
2454 return function () {
2455 if ( !hasPendingWrite
) {
2456 hasPendingWrite
= true;
2457 mw
.requestIdleCallback( flushWrites
);
2466 * HTML construction helper functions
2473 * output = Html.element( 'div', {}, new Html.Raw(
2474 * Html.element( 'img', { src: '<' } )
2476 * mw.log( output ); // <div><img src="<"/></div>
2481 html
: ( function () {
2482 function escapeCallback( s
) {
2499 * Escape a string for HTML.
2501 * Converts special characters to HTML entities.
2503 * mw.html.escape( '< > \' & "' );
2504 * // Returns < > ' & "
2506 * @param {string} s The string to escape
2507 * @return {string} HTML
2509 escape: function ( s
) {
2510 return s
.replace( /['"<>&]/g, escapeCallback
);
2514 * Create an HTML element string, with safe escaping.
2516 * @param {string} name The tag name.
2517 * @param {Object} [attrs] An object with members mapping element names to values
2518 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2520 * - string: Text to be escaped.
2521 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2522 * - this.Raw: The raw value is directly included.
2523 * - this.Cdata: The raw value is directly included. An exception is
2524 * thrown if it contains any illegal ETAGO delimiter.
2525 * See <http://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2526 * @return {string} HTML
2528 element: function ( name
, attrs
, contents
) {
2529 var v
, attrName
, s
= '<' + name
;
2532 for ( attrName
in attrs
) {
2533 v
= attrs
[ attrName
];
2534 // Convert name=true, to name=name
2538 } else if ( v
=== false ) {
2541 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2544 if ( contents
=== undefined || contents
=== null ) {
2551 switch ( typeof contents
) {
2554 s
+= this.escape( contents
);
2558 // Convert to string
2559 s
+= String( contents
);
2562 if ( contents
instanceof this.Raw
) {
2563 // Raw HTML inclusion
2564 s
+= contents
.value
;
2565 } else if ( contents
instanceof this.Cdata
) {
2567 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2568 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2570 s
+= contents
.value
;
2572 throw new Error( 'mw.html.element: Invalid type of contents' );
2575 s
+= '</' + name
+ '>';
2580 * Wrapper object for raw HTML passed to mw.html.element().
2582 * @class mw.html.Raw
2584 Raw: function ( value
) {
2589 * Wrapper object for CDATA element contents passed to mw.html.element()
2591 * @class mw.html.Cdata
2593 Cdata: function ( value
) {
2599 // Skeleton user object, extended by the 'mediawiki.user' module.
2606 * @property {mw.Map}
2610 * @property {mw.Map}
2615 // OOUI widgets specific to MediaWiki
2619 * Registry and firing of events.
2621 * MediaWiki has various interface components that are extended, enhanced
2622 * or manipulated in some other way by extensions, gadgets and even
2625 * This framework helps streamlining the timing of when these other
2626 * code paths fire their plugins (instead of using document-ready,
2627 * which can and should be limited to firing only once).
2629 * Features like navigating to other wiki pages, previewing an edit
2630 * and editing itself – without a refresh – can then retrigger these
2631 * hooks accordingly to ensure everything still works as expected.
2635 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2636 * mw.hook( 'wikipage.content' ).fire( $content );
2638 * Handlers can be added and fired for arbitrary event names at any time. The same
2639 * event can be fired multiple times. The last run of an event is memorized
2640 * (similar to `$(document).ready` and `$.Deferred().done`).
2641 * This means if an event is fired, and a handler added afterwards, the added
2642 * function will be fired right away with the last given event data.
2644 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2645 * Thus allowing flexible use and optimal maintainability and authority control.
2646 * You can pass around the `add` and/or `fire` method to another piece of code
2647 * without it having to know the event name (or `mw.hook` for that matter).
2649 * var h = mw.hook( 'bar.ready' );
2650 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2652 * Note: Events are documented with an underscore instead of a dot in the event
2653 * name due to jsduck not supporting dots in that position.
2657 hook
: ( function () {
2661 * Create an instance of mw.hook.
2665 * @param {string} name Name of hook.
2668 return function ( name
) {
2669 var list
= hasOwn
.call( lists
, name
) ?
2671 lists
[ name
] = $.Callbacks( 'memory' );
2675 * Register a hook handler
2677 * @param {...Function} handler Function to bind.
2683 * Unregister a hook handler
2685 * @param {...Function} handler Function to unbind.
2688 remove
: list
.remove
,
2693 * @param {...Mixed} data
2697 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2704 // Alias $j to jQuery for backwards compatibility
2705 // @deprecated since 1.23 Use $ or jQuery instead
2706 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2709 * Log a message to window.console, if possible.
2711 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2712 * also in production mode). Gets console references in each invocation instead of caching the
2713 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2716 * @param {string} topic Stream name passed by mw.track
2717 * @param {Object} data Data passed by mw.track
2718 * @param {Error} [data.exception]
2719 * @param {string} data.source Error source
2720 * @param {string} [data.module] Name of module which caused the error
2722 function logError( topic
, data
) {
2725 source
= data
.source
,
2726 module
= data
.module
,
2727 console
= window
.console
;
2729 if ( console
&& console
.log
) {
2730 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2732 msg
+= ' in module ' + module
;
2734 msg
+= ( e
? ':' : '.' );
2737 // If we have an exception object, log it to the error channel to trigger
2738 // proper stacktraces in browsers that support it. No fallback as we have
2739 // no browsers that don't support error(), but do support log().
2740 if ( e
&& console
.error
) {
2741 console
.error( String( e
), e
);
2746 // Subscribe to error streams
2747 mw
.trackSubscribe( 'resourceloader.exception', logError
);
2748 mw
.trackSubscribe( 'resourceloader.assert', logError
);
2751 * Fired when all modules associated with the page have finished loading.
2753 * @event resourceloader_loadEnd
2757 var loading
= $.grep( mw
.loader
.getModuleNames(), function ( module
) {
2758 return mw
.loader
.getState( module
) === 'loading';
2760 // We only need a callback, not any actual module. First try a single using()
2761 // for all loading modules. If one fails, fall back to tracking each module
2762 // separately via $.when(), this is expensive.
2763 loading
= mw
.loader
.using( loading
).then( null, function () {
2764 var all
= $.map( loading
, function ( module
) {
2765 return mw
.loader
.using( module
).then( null, function () {
2766 return $.Deferred().resolve();
2769 return $.when
.apply( $, all
);
2771 loading
.then( function () {
2772 mwPerformance
.mark( 'mwLoadEnd' );
2773 mw
.hook( 'resourceloader.loadEnd' ).fire();
2777 // Attach to window and globally alias
2778 window
.mw
= window
.mediaWiki
= mw
;