d5258131ae23b5df26124e75eb45df18763ad51b
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 via methods that allow
70 * interaction both with single and multiple properties at once.
76 * @param {boolean} [global=false] Whether to synchronise =values to the global
77 * window object (for backwards-compatibility with mw.config; T72470). Values are
78 * copied in one direction only. Changes to globals do not reflect in the map.
80 function Map( global
) {
81 this.internalValues
= {};
82 if ( global
=== true ) {
84 // Override #set to also set the global variable
85 this.set = function ( selection
, value
) {
88 if ( $.isPlainObject( selection
) ) {
89 for ( s
in selection
) {
90 setGlobalMapValue( this, s
, selection
[ s
] );
94 if ( typeof selection
=== 'string' && arguments
.length
) {
95 setGlobalMapValue( this, selection
, value
);
102 // Deprecated since MediaWiki 1.28
107 'mw.Map#values is deprecated. Use mw.Map#get() instead.',
113 * Alias property to the global object.
117 * @param {mw.Map} map
118 * @param {string} key
119 * @param {Mixed} value
121 function setGlobalMapValue( map
, key
, value
) {
122 map
.internalValues
[ key
] = value
;
127 // Deprecation notice for mw.config globals (T58550, T72470)
128 map
=== mw
.config
&& 'Use mw.config instead.'
136 * Get the value of one or more keys.
138 * If called with no arguments, all values are returned.
140 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
141 * @param {Mixed} [fallback=null] Value for keys that don't exist.
142 * @return {Mixed|Object| null} If selection was a string, returns the value,
143 * If selection was an array, returns an object of key/values.
144 * If no selection is passed, the internal container is returned. (Beware that,
145 * as is the default in JavaScript, the object is returned by reference.)
147 get: function ( selection
, fallback
) {
149 // If we only do this in the `return` block, it'll fail for the
150 // call to get() from the mutli-selection block.
151 fallback
= arguments
.length
> 1 ? fallback
: null;
153 if ( $.isArray( selection
) ) {
154 selection
= slice
.call( selection
);
156 for ( i
= 0; i
< selection
.length
; i
++ ) {
157 results
[ selection
[ i
] ] = this.get( selection
[ i
], fallback
);
162 if ( typeof selection
=== 'string' ) {
163 if ( !hasOwn
.call( this.internalValues
, selection
) ) {
166 return this.internalValues
[ selection
];
169 if ( selection
=== undefined ) {
170 return this.internalValues
;
173 // Invalid selection key
178 * Set one or more key/value pairs.
180 * @param {string|Object} selection Key to set value for, or object mapping keys to values
181 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
182 * @return {boolean} True on success, false on failure
184 set: function ( selection
, value
) {
187 if ( $.isPlainObject( selection
) ) {
188 for ( s
in selection
) {
189 this.internalValues
[ s
] = selection
[ s
];
193 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
194 this.internalValues
[ selection
] = value
;
201 * Check if one or more keys exist.
203 * @param {Mixed} selection Key or array of keys to check
204 * @return {boolean} True if the key(s) exist
206 exists: function ( selection
) {
209 if ( $.isArray( selection
) ) {
210 for ( s
= 0; s
< selection
.length
; s
++ ) {
211 if ( typeof selection
[ s
] !== 'string' || !hasOwn
.call( this.internalValues
, selection
[ s
] ) ) {
217 return typeof selection
=== 'string' && hasOwn
.call( this.internalValues
, selection
);
222 * Object constructor for messages.
224 * Similar to the Message class in MediaWiki PHP.
226 * Format defaults to 'text'.
232 * 'hello': 'Hello world',
233 * 'hello-user': 'Hello, $1!',
234 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
237 * obj = new mw.Message( mw.messages, 'hello' );
238 * mw.log( obj.text() );
241 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
242 * mw.log( obj.text() );
243 * // Hello, John Doe!
245 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
246 * mw.log( obj.text() );
247 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
249 * // Using mw.message shortcut
250 * obj = mw.message( 'hello-user', 'John Doe' );
251 * mw.log( obj.text() );
252 * // Hello, John Doe!
254 * // Using mw.msg shortcut
255 * str = mw.msg( 'hello-user', 'John Doe' );
257 * // Hello, John Doe!
259 * // Different formats
260 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
262 * obj.format = 'text';
263 * str = obj.toString();
268 * // Hello, John "Wiki" <3 Doe!
270 * mw.log( obj.escaped() );
271 * // Hello, John "Wiki" <3 Doe!
276 * @param {mw.Map} map Message store
277 * @param {string} key
278 * @param {Array} [parameters]
280 function Message( map
, key
, parameters
) {
281 this.format
= 'text';
284 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
288 Message
.prototype = {
290 * Get parsed contents of the message.
292 * The default parser does simple $N replacements and nothing else.
293 * This may be overridden to provide a more complex message parser.
294 * The primary override is in the mediawiki.jqueryMsg module.
296 * This function will not be called for nonexistent messages.
298 * @return {string} Parsed message
300 parser: function () {
301 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
305 * Add (does not replace) parameters for `$N` placeholder values.
307 * @param {Array} parameters
310 params: function ( parameters
) {
312 for ( i
= 0; i
< parameters
.length
; i
++ ) {
313 this.parameters
.push( parameters
[ i
] );
319 * Convert message object to its string form based on current format.
321 * @return {string} Message as a string in the current form, or `<key>` if key
324 toString: function () {
327 if ( !this.exists() ) {
328 // Use ⧼key⧽ as text if key does not exist
329 // Err on the side of safety, ensure that the output
330 // is always html safe in the event the message key is
331 // missing, since in that case its highly likely the
332 // message key is user-controlled.
333 // '⧼' is used instead of '<' to side-step any
334 // double-escaping issues.
335 // (Keep synchronised with Message::toString() in PHP.)
336 return '⧼' + mw
.html
.escape( this.key
) + '⧽';
339 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
340 text
= this.parser();
343 if ( this.format
=== 'escaped' ) {
344 text
= this.parser();
345 text
= mw
.html
.escape( text
);
352 * Change format to 'parse' and convert message to string
354 * If jqueryMsg is loaded, this parses the message text from wikitext
355 * (where supported) to HTML
357 * Otherwise, it is equivalent to plain.
359 * @return {string} String form of parsed message
362 this.format
= 'parse';
363 return this.toString();
367 * Change format to 'plain' and convert message to string
369 * This substitutes parameters, but otherwise does not change the
372 * @return {string} String form of plain message
375 this.format
= 'plain';
376 return this.toString();
380 * Change format to 'text' and convert message to string
382 * If jqueryMsg is loaded, {{-transformation is done where supported
383 * (such as {{plural:}}, {{gender:}}, {{int:}}).
385 * Otherwise, it is equivalent to plain
387 * @return {string} String form of text message
390 this.format
= 'text';
391 return this.toString();
395 * Change the format to 'escaped' and convert message to string
397 * This is equivalent to using the 'text' format (see #text), then
398 * HTML-escaping the output.
400 * @return {string} String form of html escaped message
402 escaped: function () {
403 this.format
= 'escaped';
404 return this.toString();
408 * Check if a message exists
413 exists: function () {
414 return this.map
.exists( this.key
);
418 log
= ( function () {
419 // Also update the restoration of methods in mediawiki.log.js
420 // when adding or removing methods here.
421 var log = function () {},
422 console
= window
.console
;
430 * Write a message to the console's warning channel.
431 * Actions not supported by the browser console are silently ignored.
433 * @param {...string} msg Messages to output to console
435 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
436 Function
.prototype.bind
.call( console
.warn
, console
) :
440 * Write a message to the console's error channel.
442 * Most browsers provide a stacktrace by default if the argument
443 * is a caught Error object.
446 * @param {Error|...string} msg Messages to output to console
448 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
449 Function
.prototype.bind
.call( console
.error
, console
) :
453 * Create a property in a host object that, when accessed, will produce
454 * a deprecation warning in the console.
456 * @param {Object} obj Host object of deprecated property
457 * @param {string} key Name of property to create in `obj`
458 * @param {Mixed} val The value this property should return when accessed
459 * @param {string} [msg] Optional text to include in the deprecation message
460 * @param {string} [logName=key] Optional custom name for the feature.
461 * This is used instead of `key` in the message and `mw.deprecate` tracking.
463 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
465 } : function ( obj
, key
, val
, msg
, logName
) {
466 logName
= logName
|| key
;
467 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
468 var logged
= new StringSet();
469 function uniqueTrace() {
470 var trace
= new Error().stack
;
471 if ( logged
.has( trace
) ) {
477 // Support: Safari 5.0
478 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
479 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
481 Object
.defineProperty( obj
, key
, {
485 if ( uniqueTrace() ) {
486 mw
.track( 'mw.deprecate', logName
);
491 set: function ( newVal
) {
492 if ( uniqueTrace() ) {
493 mw
.track( 'mw.deprecate', logName
);
513 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
515 * On browsers that implement the Navigation Timing API, this function will produce floating-point
516 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
517 * it will fall back to using `Date`.
519 * @return {number} Current time
522 var perf
= window
.performance
,
523 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
524 return navStart
&& typeof perf
.now
=== 'function' ?
525 function () { return navStart
+ perf
.now(); } :
526 function () { return +new Date(); };
530 * Format a string. Replace $1, $2 ... $N with positional arguments.
532 * Used by Message#parser().
535 * @param {string} formatString Format string
536 * @param {...Mixed} parameters Values for $N replacements
537 * @return {string} Formatted string
539 format: function ( formatString
) {
540 var parameters
= slice
.call( arguments
, 1 );
541 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
542 var index
= parseInt( match
, 10 ) - 1;
543 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
548 * Track an analytic event.
550 * This method provides a generic means for MediaWiki JavaScript code to capture state
551 * information for analysis. Each logged event specifies a string topic name that describes
552 * the kind of event that it is. Topic names consist of dot-separated path components,
553 * arranged from most general to most specific. Each path component should have a clear and
554 * well-defined purpose.
556 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
557 * events that match their subcription, including those that fired before the handler was
560 * @param {string} topic Topic name
561 * @param {Object} [data] Data describing the event, encoded as an object
563 track: function ( topic
, data
) {
564 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
565 trackCallbacks
.fire( trackQueue
);
569 * Register a handler for subset of analytic events, specified by topic.
571 * Handlers will be called once for each tracked event, including any events that fired before the
572 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
573 * the exact time at which the event fired, a string 'topic' property naming the event, and a
574 * 'data' property which is an object of event-specific data. The event topic and event data are
575 * also passed to the callback as the first and second arguments, respectively.
577 * @param {string} topic Handle events whose name starts with this string prefix
578 * @param {Function} callback Handler to call for each matching tracked event
579 * @param {string} callback.topic
580 * @param {Object} [callback.data]
582 trackSubscribe: function ( topic
, callback
) {
584 function handler( trackQueue
) {
586 for ( ; seen
< trackQueue
.length
; seen
++ ) {
587 event
= trackQueue
[ seen
];
588 if ( event
.topic
.indexOf( topic
) === 0 ) {
589 callback
.call( event
, event
.topic
, event
.data
);
594 trackHandlers
.push( [ handler
, callback
] );
596 trackCallbacks
.add( handler
);
600 * Stop handling events for a particular handler
602 * @param {Function} callback
604 trackUnsubscribe: function ( callback
) {
605 trackHandlers
= $.grep( trackHandlers
, function ( fns
) {
606 if ( fns
[ 1 ] === callback
) {
607 trackCallbacks
.remove( fns
[ 0 ] );
608 // Ensure the tuple is removed to avoid holding on to closures
615 // Expose Map constructor
618 // Expose Message constructor
622 * Map of configuration values.
624 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
627 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
628 * global `window` object.
630 * @property {mw.Map} config
632 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
636 * Empty object for third-party libraries, for cases where you don't
637 * want to add a new global, or the global is bad and needs containment
645 * Access container for deprecated functionality that can be moved from
646 * from their legacy location and attached to this object (e.g. a global
647 * function that is deprecated and as stop-gap can be exposed through here).
649 * This was reserved for future use but never ended up being used.
651 * @deprecated since 1.22 Let deprecated identifiers keep their original name
652 * and use mw.log#deprecate to create an access container for tracking.
658 * Store for messages.
665 * Store for templates associated with a module.
669 templates
: new Map(),
672 * Get a message object.
674 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
677 * @param {string} key Key of message to get
678 * @param {...Mixed} parameters Values for $N replacements
679 * @return {mw.Message}
681 message: function ( key
) {
682 var parameters
= slice
.call( arguments
, 1 );
683 return new Message( mw
.messages
, key
, parameters
);
687 * Get a message string using the (default) 'text' format.
689 * Shortcut for `mw.message( key, parameters... ).text()`.
692 * @param {string} key Key of message to get
693 * @param {...Mixed} parameters Values for $N replacements
697 return mw
.message
.apply( mw
.message
, arguments
).toString();
701 * No-op dummy placeholder for {@link mw.log} in debug mode.
708 * Client for ResourceLoader server end point.
710 * This client is in charge of maintaining the module registry and state
711 * machine, initiating network (batch) requests for loading modules, as
712 * well as dependency resolution and execution of source code.
714 * For more information, refer to
715 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
720 loader
: ( function () {
723 * Fired via mw.track on various resource loading errors.
725 * @event resourceloader_exception
726 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
727 * object, but in theory module code could manually throw something else, and that
728 * might also end up here.
729 * @param {string} [module] Name of the module which caused the error. Omitted if the
730 * error is not module-related or the module cannot be easily identified due to
732 * @param {string} source Source of the error. Possible values:
734 * - style: stylesheet error (only affects old IE where a special style loading method
736 * - load-callback: exception thrown by user callback
737 * - module-execute: exception thrown by module code
738 * - store-eval: could not evaluate module code cached in localStorage
739 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
740 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
741 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
745 * Fired via mw.track on resource loading error conditions.
747 * @event resourceloader_assert
748 * @param {string} source Source of the error. Possible values:
750 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
751 * bug; see <https://phabricator.wikimedia.org/T59567> for details
755 * Mapping of registered modules.
757 * See #implement and #execute for exact details on support for script, style and messages.
763 * // From mw.loader.register()
764 * 'version': '########' (hash)
765 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
766 * 'group': 'somegroup', (or) null
767 * 'source': 'local', (or) 'anotherwiki'
768 * 'skip': 'return !!window.Example', (or) null
769 * 'module': export Object
771 * // Set from execute() or mw.loader.state()
772 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
774 * // Optionally added at run-time by mw.loader.implement()
776 * 'script': closure, array of urls, or string
777 * 'style': { ... } (see #execute)
778 * 'messages': { 'key': 'value', ... }
785 * The module is known to the system but not yet required.
786 * Meta data is registered via mw.loader#register. Calls to that method are
787 * generated server-side by the startup module.
789 * The module was required through mw.loader (either directly or as dependency of
790 * another module). The client will fetch module contents from the server.
791 * The contents are then stashed in the registry via mw.loader#implement.
793 * The module has been loaded from the server and stashed via mw.loader#implement.
794 * If the module has no more dependencies in-flight, the module will be executed
795 * immediately. Otherwise execution is deferred, controlled via #handlePending.
797 * The module is being executed.
799 * The module has been successfully executed.
801 * The module (or one of its dependencies) produced an error during execution.
803 * The module was registered client-side and requested, but the server denied knowledge
804 * of the module's existence.
810 // Mapping of sources, keyed by source-id, values are strings.
815 // 'sourceId': 'http://example.org/w/load.php'
820 // For queueModuleScript()
821 handlingPendingRequests
= false,
822 pendingRequests
= [],
824 // List of modules to be loaded
828 * List of callback jobs waiting for modules to be ready.
830 * Jobs are created by #enqueue() and run by #handlePending().
832 * Typically when a job is created for a module, the job's dependencies contain
833 * both the required module and all its recursive dependencies.
838 * 'dependencies': [ module names ],
839 * 'ready': Function callback
840 * 'error': Function callback
843 * @property {Object[]} jobs
851 // For addEmbeddedCSS()
853 cssBufferTimer
= null,
854 cssCallbacks
= $.Callbacks(),
855 isIE9
= document
.documentMode
=== 9,
856 rAF
= window
.requestAnimationFrame
|| setTimeout
;
858 function getMarker() {
861 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
863 mw
.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
864 marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
871 * Create a new style element and add it to the DOM.
874 * @param {string} text CSS text
875 * @param {Node} [nextNode] The element where the style tag
876 * should be inserted before
877 * @return {HTMLElement} Reference to the created style element
879 function newStyleTag( text
, nextNode
) {
880 var s
= document
.createElement( 'style' );
882 s
.appendChild( document
.createTextNode( text
) );
883 if ( nextNode
&& nextNode
.parentNode
) {
884 nextNode
.parentNode
.insertBefore( s
, nextNode
);
886 document
.getElementsByTagName( 'head' )[ 0 ].appendChild( s
);
893 * Add a bit of CSS text to the current browser page.
895 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
896 * or create a new one based on whether the given `cssText` is safe for extension.
899 * @param {string} [cssText=cssBuffer] If called without cssText,
900 * the internal buffer will be inserted instead.
901 * @param {Function} [callback]
903 function addEmbeddedCSS( cssText
, callback
) {
906 function fireCallbacks() {
907 var oldCallbacks
= cssCallbacks
;
908 // Reset cssCallbacks variable so it's not polluted by any calls to
909 // addEmbeddedCSS() from one of the callbacks (T105973)
910 cssCallbacks
= $.Callbacks();
911 oldCallbacks
.fire().empty();
915 cssCallbacks
.add( callback
);
918 // Yield once before creating the <style> tag. This lets multiple stylesheets
919 // accumulate into one buffer, allowing us to reduce how often new stylesheets
920 // are inserted in the browser. Appending a stylesheet and waiting for the
921 // browser to repaint is fairly expensive. (T47810)
923 // Don't extend the buffer if the item needs its own stylesheet.
924 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
925 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
926 // Linebreak for somewhat distinguishable sections
927 cssBuffer
+= '\n' + cssText
;
928 if ( !cssBufferTimer
) {
929 cssBufferTimer
= rAF( function () {
930 // Wrap in anonymous function that takes no arguments
931 // Support: Firefox < 13
932 // Firefox 12 has non-standard behaviour of passing a number
933 // as first argument to a setTimeout callback.
934 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
941 // This is a scheduled flush for the buffer
943 cssBufferTimer
= null;
948 // By default, always create a new <style>. Appending text to a <style> tag is
949 // is a performance anti-pattern as it requires CSS to be reparsed (T47810).
952 // Try to re-use existing <style> tags due to the IE stylesheet limit (T33676).
954 $style
= $( getMarker() ).prev();
955 // Verify that the element before the marker actually is a <style> tag created
956 // by mw.loader (not some other style tag, or e.g. a <meta> tag).
957 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) ) {
958 styleEl
= $style
[ 0 ];
959 styleEl
.appendChild( document
.createTextNode( cssText
) );
963 // Else: No existing tag to reuse. Continue below and create the first one.
966 $style
= $( newStyleTag( cssText
, getMarker() ) );
969 $style
.data( 'ResourceLoaderDynamicStyleTag', true );
977 * @param {Array} modules List of module names
978 * @return {string} Hash of concatenated version hashes.
980 function getCombinedVersion( modules
) {
981 var hashes
= $.map( modules
, function ( module
) {
982 return registry
[ module
].version
;
984 return fnv132( hashes
.join( '' ) );
988 * Determine whether all dependencies are in state 'ready', which means we may
989 * execute the module or job now.
992 * @param {Array} modules Names of modules to be checked
993 * @return {boolean} True if all modules are in state 'ready', false otherwise
995 function allReady( modules
) {
997 for ( i
= 0; i
< modules
.length
; i
++ ) {
998 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
1006 * Determine whether all dependencies are in state 'ready', which means we may
1007 * execute the module or job now.
1010 * @param {Array} modules Names of modules to be checked
1011 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1013 function anyFailed( modules
) {
1015 for ( i
= 0; i
< modules
.length
; i
++ ) {
1016 state
= mw
.loader
.getState( modules
[ i
] );
1017 if ( state
=== 'error' || state
=== 'missing' ) {
1025 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1026 * pending jobs and modules that depend upon this module. If the given module failed,
1027 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1028 * all jobs/modules now having their dependencies satisfied.
1030 * Jobs that depend on a failed module, will have their error callback ran (if any).
1033 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1035 function handlePending( module
) {
1036 var j
, job
, hasErrors
, m
, stateChange
;
1038 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1039 // If the current module failed, mark all dependent modules also as failed.
1040 // Iterate until steady-state to propagate the error state upwards in the
1043 stateChange
= false;
1044 for ( m
in registry
) {
1045 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1046 if ( anyFailed( registry
[ m
].dependencies
) ) {
1047 registry
[ m
].state
= 'error';
1052 } while ( stateChange
);
1055 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1056 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1057 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1058 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1059 // All dependencies satisfied, or some have errors
1061 jobs
.splice( j
, 1 );
1065 if ( typeof job
.error
=== 'function' ) {
1066 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1069 if ( typeof job
.ready
=== 'function' ) {
1074 // A user-defined callback raised an exception.
1075 // Swallow it to protect our state machine!
1076 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1081 if ( registry
[ module
].state
=== 'ready' ) {
1082 // The current module became 'ready'. Set it in the module store, and recursively execute all
1083 // dependent modules that are loaded and now have all dependencies satisfied.
1084 mw
.loader
.store
.set( module
, registry
[ module
] );
1085 for ( m
in registry
) {
1086 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1094 * Resolve dependencies and detect circular references.
1097 * @param {string} module Name of the top-level module whose dependencies shall be
1098 * resolved and sorted.
1099 * @param {Array} resolved Returns a topological sort of the given module and its
1100 * dependencies, such that later modules depend on earlier modules. The array
1101 * contains the module names. If the array contains already some module names,
1102 * this function appends its result to the pre-existing array.
1103 * @param {StringSet} [unresolved] Used to track the current dependency
1104 * chain, and to report loops in the dependency graph.
1105 * @throws {Error} If any unregistered module or a dependency loop is encountered
1107 function sortDependencies( module
, resolved
, unresolved
) {
1110 if ( !hasOwn
.call( registry
, module
) ) {
1111 throw new Error( 'Unknown dependency: ' + module
);
1114 if ( registry
[ module
].skip
!== null ) {
1115 /*jshint evil:true */
1116 skip
= new Function( registry
[ module
].skip
);
1117 registry
[ module
].skip
= null;
1119 registry
[ module
].skipped
= true;
1120 registry
[ module
].dependencies
= [];
1121 registry
[ module
].state
= 'ready';
1122 handlePending( module
);
1127 // Resolves dynamic loader function and replaces it with its own results
1128 if ( typeof registry
[ module
].dependencies
=== 'function' ) {
1129 registry
[ module
].dependencies
= registry
[ module
].dependencies();
1130 // Ensures the module's dependencies are always in an array
1131 if ( typeof registry
[ module
].dependencies
!== 'object' ) {
1132 registry
[ module
].dependencies
= [ registry
[ module
].dependencies
];
1135 if ( $.inArray( module
, resolved
) !== -1 ) {
1136 // Module already resolved; nothing to do
1139 // Create unresolved if not passed in
1140 if ( !unresolved
) {
1141 unresolved
= new StringSet();
1143 // Tracks down dependencies
1144 deps
= registry
[ module
].dependencies
;
1145 for ( i
= 0; i
< deps
.length
; i
++ ) {
1146 if ( $.inArray( deps
[ i
], resolved
) === -1 ) {
1147 if ( unresolved
.has( deps
[ i
] ) ) {
1148 throw new Error( mw
.format(
1149 'Circular reference detected: $1 -> $2',
1155 unresolved
.add( module
);
1156 sortDependencies( deps
[ i
], resolved
, unresolved
);
1159 resolved
.push( module
);
1163 * Get names of module that a module depends on, in their proper dependency order.
1166 * @param {string[]} modules Array of string module names
1167 * @return {Array} List of dependencies, including 'module'.
1169 function resolve( modules
) {
1171 $.each( modules
, function ( idx
, module
) {
1172 sortDependencies( module
, resolved
);
1178 * Load and execute a script.
1181 * @param {string} src URL to script, will be used as the src attribute in the script tag
1182 * @return {jQuery.Promise}
1184 function addScript( src
) {
1188 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1189 // XHR for a same domain request instead of <script>, which changes the request
1190 // headers (potentially missing a cache hit), and reduces caching in general
1191 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1192 // text, so we'd need to $.globalEval, which then messes up line numbers.
1199 * Queue the loading and execution of a script for a particular module.
1202 * @param {string} src URL of the script
1203 * @param {string} [moduleName] Name of currently executing module
1204 * @return {jQuery.Promise}
1206 function queueModuleScript( src
, moduleName
) {
1207 var r
= $.Deferred();
1209 pendingRequests
.push( function () {
1210 if ( moduleName
&& hasOwn
.call( registry
, moduleName
) ) {
1211 // Emulate runScript() part of execute()
1212 window
.require
= mw
.loader
.require
;
1213 window
.module
= registry
[ moduleName
].module
;
1215 addScript( src
).always( function () {
1216 // 'module.exports' should not persist after the file is executed to
1217 // avoid leakage to unrelated code. 'require' should be kept, however,
1218 // as asynchronous access to 'require' is allowed and expected. (T144879)
1219 delete window
.module
;
1222 // Start the next one (if any)
1223 if ( pendingRequests
[ 0 ] ) {
1224 pendingRequests
.shift()();
1226 handlingPendingRequests
= false;
1230 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1231 handlingPendingRequests
= true;
1232 pendingRequests
.shift()();
1238 * Utility function for execute()
1242 function addLink( media
, url
) {
1243 var el
= document
.createElement( 'link' );
1245 el
.rel
= 'stylesheet';
1246 if ( media
&& media
!== 'all' ) {
1249 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1250 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1253 $( getMarker() ).before( el
);
1257 * Executes a loaded module, making it ready to use
1260 * @param {string} module Module name to execute
1262 function execute( module
) {
1263 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1264 cssHandlesRegistered
= false;
1266 if ( !hasOwn
.call( registry
, module
) ) {
1267 throw new Error( 'Module has not been registered yet: ' + module
);
1269 if ( registry
[ module
].state
!== 'loaded' ) {
1270 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1273 registry
[ module
].state
= 'executing';
1275 runScript = function () {
1276 var script
, markModuleReady
, nestedAddScript
, legacyWait
, implicitDependencies
,
1277 // Expand to include dependencies since we have to exclude both legacy modules
1278 // and their dependencies from the legacyWait (to prevent a circular dependency).
1279 legacyModules
= resolve( mw
.config
.get( 'wgResourceLoaderLegacyModules', [] ) );
1281 script
= registry
[ module
].script
;
1282 markModuleReady = function () {
1283 registry
[ module
].state
= 'ready';
1284 handlePending( module
);
1286 nestedAddScript = function ( arr
, callback
, i
) {
1287 // Recursively call queueModuleScript() in its own callback
1288 // for each element of arr.
1289 if ( i
>= arr
.length
) {
1290 // We're at the end of the array
1295 queueModuleScript( arr
[ i
], module
).always( function () {
1296 nestedAddScript( arr
, callback
, i
+ 1 );
1300 implicitDependencies
= ( $.inArray( module
, legacyModules
) !== -1 )
1304 if ( module
=== 'user' ) {
1305 // Implicit dependency on the site module. Not real dependency because
1306 // it should run after 'site' regardless of whether it succeeds or fails.
1307 implicitDependencies
.push( 'site' );
1310 legacyWait
= implicitDependencies
.length
1311 ? mw
.loader
.using( implicitDependencies
)
1312 : $.Deferred().resolve();
1314 legacyWait
.always( function () {
1316 if ( $.isArray( script
) ) {
1317 nestedAddScript( script
, markModuleReady
, 0 );
1318 } else if ( typeof script
=== 'function' ) {
1319 // Pass jQuery twice so that the signature of the closure which wraps
1320 // the script can bind both '$' and 'jQuery'.
1321 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1324 } else if ( typeof script
=== 'string' ) {
1325 // Site and user modules are legacy scripts that run in the global scope.
1326 // This is transported as a string instead of a function to avoid needing
1327 // to use string manipulation to undo the function wrapper.
1328 $.globalEval( script
);
1332 // Module without script
1336 // Use mw.track instead of mw.log because these errors are common in production mode
1337 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1338 registry
[ module
].state
= 'error';
1339 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1340 handlePending( module
);
1345 // Add localizations to message system
1346 if ( registry
[ module
].messages
) {
1347 mw
.messages
.set( registry
[ module
].messages
);
1350 // Initialise templates
1351 if ( registry
[ module
].templates
) {
1352 mw
.templates
.set( module
, registry
[ module
].templates
);
1355 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1358 checkCssHandles = function () {
1359 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1360 // one of the cssHandles is fired while we're still creating more handles.
1361 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1363 runScript
= undefined; // Revoke
1366 cssHandle = function () {
1367 var check
= checkCssHandles
;
1369 return function () {
1373 check
= undefined; // Revoke
1379 // Process styles (see also mw.loader.implement)
1380 // * back-compat: { <media>: css }
1381 // * back-compat: { <media>: [url, ..] }
1382 // * { "css": [css, ..] }
1383 // * { "url": { <media>: [url, ..] } }
1384 if ( registry
[ module
].style
) {
1385 for ( key
in registry
[ module
].style
) {
1386 value
= registry
[ module
].style
[ key
];
1389 if ( key
!== 'url' && key
!== 'css' ) {
1390 // Backwards compatibility, key is a media-type
1391 if ( typeof value
=== 'string' ) {
1392 // back-compat: { <media>: css }
1393 // Ignore 'media' because it isn't supported (nor was it used).
1394 // Strings are pre-wrapped in "@media". The media-type was just ""
1395 // (because it had to be set to something).
1396 // This is one of the reasons why this format is no longer used.
1397 addEmbeddedCSS( value
, cssHandle() );
1399 // back-compat: { <media>: [url, ..] }
1405 // Array of css strings in key 'css',
1406 // or back-compat array of urls from media-type
1407 if ( $.isArray( value
) ) {
1408 for ( i
= 0; i
< value
.length
; i
++ ) {
1409 if ( key
=== 'bc-url' ) {
1410 // back-compat: { <media>: [url, ..] }
1411 addLink( media
, value
[ i
] );
1412 } else if ( key
=== 'css' ) {
1413 // { "css": [css, ..] }
1414 addEmbeddedCSS( value
[ i
], cssHandle() );
1417 // Not an array, but a regular object
1418 // Array of urls inside media-type key
1419 } else if ( typeof value
=== 'object' ) {
1420 // { "url": { <media>: [url, ..] } }
1421 for ( media
in value
) {
1422 urls
= value
[ media
];
1423 for ( i
= 0; i
< urls
.length
; i
++ ) {
1424 addLink( media
, urls
[ i
] );
1432 cssHandlesRegistered
= true;
1437 * Add one or more modules to the module load queue.
1442 * @param {string|string[]} dependencies Module name or array of string module names
1443 * @param {Function} [ready] Callback to execute when all dependencies are ready
1444 * @param {Function} [error] Callback to execute when any dependency fails
1446 function enqueue( dependencies
, ready
, error
) {
1447 // Allow calling by single module name
1448 if ( typeof dependencies
=== 'string' ) {
1449 dependencies
= [ dependencies
];
1452 // Add ready and error callbacks if they were given
1453 if ( ready
!== undefined || error
!== undefined ) {
1455 // Narrow down the list to modules that are worth waiting for
1456 dependencies
: $.grep( dependencies
, function ( module
) {
1457 var state
= mw
.loader
.getState( module
);
1458 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1465 $.each( dependencies
, function ( idx
, module
) {
1466 var state
= mw
.loader
.getState( module
);
1467 // Only queue modules that are still in the initial 'registered' state
1468 // (not ones already loading, ready or error).
1469 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1470 // Private modules must be embedded in the page. Don't bother queuing
1471 // these as the server will deny them anyway (T101806).
1472 if ( registry
[ module
].group
=== 'private' ) {
1473 registry
[ module
].state
= 'error';
1474 handlePending( module
);
1477 queue
.push( module
);
1484 function sortQuery( o
) {
1490 if ( hasOwn
.call( o
, key
) ) {
1495 for ( key
= 0; key
< a
.length
; key
++ ) {
1496 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1502 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1503 * to a query string of the form foo.bar,baz|bar.baz,quux
1507 function buildModulesString( moduleMap
) {
1511 for ( prefix
in moduleMap
) {
1512 p
= prefix
=== '' ? '' : prefix
+ '.';
1513 arr
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1515 return arr
.join( '|' );
1519 * Make a network request to load modules from the server.
1522 * @param {Object} moduleMap Module map, see #buildModulesString
1523 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1524 * @param {string} sourceLoadScript URL of load.php
1526 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
1527 var query
= $.extend(
1528 { modules
: buildModulesString( moduleMap
) },
1531 query
= sortQuery( query
);
1532 addScript( sourceLoadScript
+ '?' + $.param( query
) );
1536 * Resolve indexed dependencies.
1538 * ResourceLoader uses an optimization to save space which replaces module names in
1539 * dependency lists with the index of that module within the array of module
1540 * registration data if it exists. The benefit is a significant reduction in the data
1541 * size of the startup module. This function changes those dependency lists back to
1542 * arrays of strings.
1545 * @param {Array} modules Modules array
1547 function resolveIndexedDependencies( modules
) {
1549 function resolveIndex( dep
) {
1550 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1552 for ( i
= 0; i
< modules
.length
; i
++ ) {
1553 deps
= modules
[ i
][ 2 ];
1555 for ( j
= 0; j
< deps
.length
; j
++ ) {
1556 deps
[ j
] = resolveIndex( deps
[ j
] );
1563 * Create network requests for a batch of modules.
1565 * This is an internal method for #work(). This must not be called directly
1566 * unless the modules are already registered, and no request is in progress,
1567 * and the module state has already been set to `loading`.
1570 * @param {string[]} batch
1572 function batchRequest( batch
) {
1573 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1574 source
, group
, i
, modules
, sourceLoadScript
,
1575 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1576 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1578 if ( !batch
.length
) {
1582 // Always order modules alphabetically to help reduce cache
1583 // misses for otherwise identical content.
1586 // Build a list of query parameters common to all requests
1588 skin
: mw
.config
.get( 'skin' ),
1589 lang
: mw
.config
.get( 'wgUserLanguage' ),
1590 debug
: mw
.config
.get( 'debug' )
1592 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1594 // Split module list by source and by group.
1596 for ( b
= 0; b
< batch
.length
; b
++ ) {
1597 bSource
= registry
[ batch
[ b
] ].source
;
1598 bGroup
= registry
[ batch
[ b
] ].group
;
1599 if ( !hasOwn
.call( splits
, bSource
) ) {
1600 splits
[ bSource
] = {};
1602 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1603 splits
[ bSource
][ bGroup
] = [];
1605 bSourceGroup
= splits
[ bSource
][ bGroup
];
1606 bSourceGroup
.push( batch
[ b
] );
1609 for ( source
in splits
) {
1611 sourceLoadScript
= sources
[ source
];
1613 for ( group
in splits
[ source
] ) {
1615 // Cache access to currently selected list of
1616 // modules for this group from this source.
1617 modules
= splits
[ source
][ group
];
1619 currReqBase
= $.extend( {
1620 version
: getCombinedVersion( modules
)
1622 // For user modules append a user name to the query string.
1623 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1624 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1626 currReqBaseLength
= $.param( currReqBase
).length
;
1627 // We may need to split up the request to honor the query string length limit,
1628 // so build it piece by piece.
1629 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1631 moduleMap
= {}; // { prefix: [ suffixes ] }
1633 for ( i
= 0; i
< modules
.length
; i
++ ) {
1634 // Determine how many bytes this module would add to the query string
1635 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1637 // If lastDotIndex is -1, substr() returns an empty string
1638 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1639 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1641 bytesAdded
= hasOwn
.call( moduleMap
, prefix
)
1642 ? suffix
.length
+ 3 // '%2C'.length == 3
1643 : modules
[ i
].length
+ 3; // '%7C'.length == 3
1645 // If the url would become too long, create a new one,
1646 // but don't create empty requests
1647 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1648 // This url would become too long, create a new one, and start the old one
1649 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1651 l
= currReqBaseLength
+ 9;
1652 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1654 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1655 moduleMap
[ prefix
] = [];
1657 moduleMap
[ prefix
].push( suffix
);
1660 // If there's anything left in moduleMap, request that too
1661 if ( !$.isEmptyObject( moduleMap
) ) {
1662 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1670 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1671 * form of calls to mw.loader#implement().
1672 * @param {Function} cb Callback in case of failure
1673 * @param {Error} cb.err
1675 function asyncEval( implementations
, cb
) {
1676 if ( !implementations
.length
) {
1679 mw
.requestIdleCallback( function () {
1681 $.globalEval( implementations
.join( ';' ) );
1689 * Make a versioned key for a specific module.
1692 * @param {string} module Module name
1693 * @return {string|null} Module key in format '`[name]@[version]`',
1694 * or null if the module does not exist
1696 function getModuleKey( module
) {
1697 return hasOwn
.call( registry
, module
) ?
1698 ( module
+ '@' + registry
[ module
].version
) : null;
1703 * @param {string} key Module name or '`[name]@[version]`'
1706 function splitModuleKey( key
) {
1707 var index
= key
.indexOf( '@' );
1708 if ( index
=== -1 ) {
1709 return { name
: key
};
1712 name
: key
.slice( 0, index
),
1713 version
: key
.slice( index
+ 1 )
1717 /* Public Members */
1720 * The module registry is exposed as an aid for debugging and inspecting page
1721 * state; it is not a public interface for modifying the registry.
1727 moduleRegistry
: registry
,
1730 * @inheritdoc #newStyleTag
1733 addStyleTag
: newStyleTag
,
1736 * Start loading of all queued module dependencies.
1741 var q
, batch
, implementations
, sourceModules
;
1745 // Appends a list of modules from the queue to the batch
1746 for ( q
= 0; q
< queue
.length
; q
++ ) {
1747 // Only load modules which are registered
1748 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1749 // Prevent duplicate entries
1750 if ( $.inArray( queue
[ q
], batch
) === -1 ) {
1751 batch
.push( queue
[ q
] );
1752 // Mark registered modules as loading
1753 registry
[ queue
[ q
] ].state
= 'loading';
1758 // Now that the queue has been processed into a batch, clear the queue.
1759 // This MUST happen before we initiate any eval or network request. Otherwise,
1760 // it is possible for a cached script to instantly trigger the same work queue
1761 // again; all before we've cleared it causing each request to include modules
1762 // which are already loaded.
1765 if ( !batch
.length
) {
1769 mw
.loader
.store
.init();
1770 if ( mw
.loader
.store
.enabled
) {
1771 implementations
= [];
1773 batch
= $.grep( batch
, function ( module
) {
1774 var implementation
= mw
.loader
.store
.get( module
);
1775 if ( implementation
) {
1776 implementations
.push( implementation
);
1777 sourceModules
.push( module
);
1782 asyncEval( implementations
, function ( err
) {
1783 // Not good, the cached mw.loader.implement calls failed! This should
1784 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1785 // Depending on how corrupt the string is, it is likely that some
1786 // modules' implement() succeeded while the ones after the error will
1787 // never run and leave their modules in the 'loading' state forever.
1788 mw
.loader
.store
.stats
.failed
++;
1790 // Since this is an error not caused by an individual module but by
1791 // something that infected the implement call itself, don't take any
1792 // risks and clear everything in this cache.
1793 mw
.loader
.store
.clear();
1795 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1796 // Re-add the failed ones that are still pending back to the batch
1797 var failed
= $.grep( sourceModules
, function ( module
) {
1798 return registry
[ module
].state
=== 'loading';
1800 batchRequest( failed
);
1804 batchRequest( batch
);
1808 * Register a source.
1810 * The #work() method will use this information to split up requests by source.
1812 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1814 * @param {string|Object} id Source ID, or object mapping ids to load urls
1815 * @param {string} loadUrl Url to a load.php end point
1816 * @throws {Error} If source id is already registered
1818 addSource: function ( id
, loadUrl
) {
1820 // Allow multiple additions
1821 if ( typeof id
=== 'object' ) {
1822 for ( source
in id
) {
1823 mw
.loader
.addSource( source
, id
[ source
] );
1828 if ( hasOwn
.call( sources
, id
) ) {
1829 throw new Error( 'source already registered: ' + id
);
1832 sources
[ id
] = loadUrl
;
1836 * Register a module, letting the system know about it and its properties.
1838 * The startup modules contain calls to this method.
1840 * When using multiple module registration by passing an array, dependencies that
1841 * are specified as references to modules within the array will be resolved before
1842 * the modules are registered.
1844 * @param {string|Array} module Module name or array of arrays, each containing
1845 * a list of arguments compatible with this method
1846 * @param {string|number} version Module version hash (falls backs to empty string)
1847 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1848 * @param {string|Array|Function} dependencies One string or array of strings of module
1849 * names on which this module depends, or a function that returns that array.
1850 * @param {string} [group=null] Group which the module is in
1851 * @param {string} [source='local'] Name of the source
1852 * @param {string} [skip=null] Script body of the skip function
1854 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1856 // Allow multiple registration
1857 if ( typeof module
=== 'object' ) {
1858 resolveIndexedDependencies( module
);
1859 for ( i
= 0; i
< module
.length
; i
++ ) {
1860 // module is an array of module names
1861 if ( typeof module
[ i
] === 'string' ) {
1862 mw
.loader
.register( module
[ i
] );
1863 // module is an array of arrays
1864 } else if ( typeof module
[ i
] === 'object' ) {
1865 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1870 if ( hasOwn
.call( registry
, module
) ) {
1871 throw new Error( 'module already registered: ' + module
);
1873 if ( typeof dependencies
=== 'string' ) {
1874 // A single module name
1875 deps
= [ dependencies
];
1876 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
1877 // Array of module names or a function that returns an array
1878 deps
= dependencies
;
1880 // List the module as registered
1881 registry
[ module
] = {
1882 // Exposed to execute() for mw.loader.implement() closures.
1883 // Import happens via require().
1887 version
: version
!== undefined ? String( version
) : '',
1888 dependencies
: deps
|| [],
1889 group
: typeof group
=== 'string' ? group
: null,
1890 source
: typeof source
=== 'string' ? source
: 'local',
1891 state
: 'registered',
1892 skip
: typeof skip
=== 'string' ? skip
: null
1897 * Implement a module given the components that make up the module.
1899 * When #load() or #using() requests one or more modules, the server
1900 * response contain calls to this function.
1902 * @param {string} module Name of module and current module version. Formatted
1903 * as '`[name]@[version]`". This version should match the requested version
1904 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1905 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1906 * @param {Function|Array|string} [script] Function with module code, list of URLs
1907 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1908 * @param {Object} [style] Should follow one of the following patterns:
1910 * { "css": [css, ..] }
1911 * { "url": { <media>: [url, ..] } }
1913 * And for backwards compatibility (needs to be supported forever due to caching):
1916 * { <media>: [url, ..] }
1918 * The reason css strings are not concatenated anymore is bug 31676. We now check
1919 * whether it's safe to extend the stylesheet.
1922 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1923 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1925 implement: function ( module
, script
, style
, messages
, templates
) {
1926 var split
= splitModuleKey( module
),
1928 version
= split
.version
;
1929 // Automatically register module
1930 if ( !hasOwn
.call( registry
, name
) ) {
1931 mw
.loader
.register( name
);
1933 // Check for duplicate implementation
1934 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1935 throw new Error( 'module already implemented: ' + name
);
1938 // Without this reset, if there is a version mismatch between the
1939 // requested and received module version, then mw.loader.store would
1940 // cache the response under the requested key. Thus poisoning the cache
1941 // indefinitely with a stale value. (T117587)
1942 registry
[ name
].version
= version
;
1944 // Attach components
1945 registry
[ name
].script
= script
|| null;
1946 registry
[ name
].style
= style
|| null;
1947 registry
[ name
].messages
= messages
|| null;
1948 registry
[ name
].templates
= templates
|| null;
1949 // The module may already have been marked as erroneous
1950 if ( $.inArray( registry
[ name
].state
, [ 'error', 'missing' ] ) === -1 ) {
1951 registry
[ name
].state
= 'loaded';
1952 if ( allReady( registry
[ name
].dependencies
) ) {
1959 * Execute a function as soon as one or more required modules are ready.
1961 * Example of inline dependency on OOjs:
1963 * mw.loader.using( 'oojs', function () {
1964 * OO.compare( [ 1 ], [ 1 ] );
1967 * Since MediaWiki 1.23 this also returns a promise.
1969 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1971 * @param {string|Array} dependencies Module name or array of modules names the
1972 * callback depends on to be ready before executing
1973 * @param {Function} [ready] Callback to execute when all dependencies are ready
1974 * @param {Function} [error] Callback to execute if one or more dependencies failed
1975 * @return {jQuery.Promise} With a `require` function
1977 using: function ( dependencies
, ready
, error
) {
1978 var deferred
= $.Deferred();
1980 // Allow calling with a single dependency as a string
1981 if ( typeof dependencies
=== 'string' ) {
1982 dependencies
= [ dependencies
];
1986 deferred
.done( ready
);
1989 deferred
.fail( error
);
1992 // Resolve entire dependency map
1993 dependencies
= resolve( dependencies
);
1994 if ( allReady( dependencies
) ) {
1995 // Run ready immediately
1996 deferred
.resolve( mw
.loader
.require
);
1997 } else if ( anyFailed( dependencies
) ) {
1998 // Execute error immediately if any dependencies have errors
2000 new Error( 'One or more dependencies failed to load' ),
2004 // Not all dependencies are ready, add to the load queue
2005 enqueue( dependencies
, function () {
2006 deferred
.resolve( mw
.loader
.require
);
2007 }, deferred
.reject
);
2010 return deferred
.promise();
2014 * Load an external script or one or more modules.
2016 * @param {string|Array} modules Either the name of a module, array of modules,
2017 * or a URL of an external script or style
2018 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2019 * external script or style; acceptable values are "text/css" and
2020 * "text/javascript"; if no type is provided, text/javascript is assumed.
2022 load: function ( modules
, type
) {
2025 // Allow calling with a url or single dependency as a string
2026 if ( typeof modules
=== 'string' ) {
2027 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2028 if ( /^(https?:)?\/?\//.test( modules
) ) {
2029 if ( type
=== 'text/css' ) {
2031 // Use properties instead of attributes as IE throws security
2032 // warnings when inserting a <link> tag with a protocol-relative
2033 // URL set though attributes - when on HTTPS. See bug 41331.
2034 l
= document
.createElement( 'link' );
2035 l
.rel
= 'stylesheet';
2037 $( 'head' ).append( l
);
2040 if ( type
=== 'text/javascript' || type
=== undefined ) {
2041 addScript( modules
);
2045 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2047 // Called with single module
2048 modules
= [ modules
];
2051 // Filter out undefined modules, otherwise resolve() will throw
2052 // an exception for trying to load an undefined module.
2053 // Undefined modules are acceptable here in load(), because load() takes
2054 // an array of unrelated modules, whereas the modules passed to
2055 // using() are related and must all be loaded.
2056 filtered
= $.grep( modules
, function ( module
) {
2057 var state
= mw
.loader
.getState( module
);
2058 return state
!== null && state
!== 'error' && state
!== 'missing';
2061 if ( filtered
.length
=== 0 ) {
2064 // Resolve entire dependency map
2065 filtered
= resolve( filtered
);
2066 // If all modules are ready, or if any modules have errors, nothing to be done.
2067 if ( allReady( filtered
) || anyFailed( filtered
) ) {
2070 // Some modules are not yet ready, add to module load queue.
2071 enqueue( filtered
, undefined, undefined );
2075 * Change the state of one or more modules.
2077 * @param {string|Object} module Module name or object of module name/state pairs
2078 * @param {string} state State name
2080 state: function ( module
, state
) {
2083 if ( typeof module
=== 'object' ) {
2084 for ( m
in module
) {
2085 mw
.loader
.state( m
, module
[ m
] );
2089 if ( !hasOwn
.call( registry
, module
) ) {
2090 mw
.loader
.register( module
);
2092 registry
[ module
].state
= state
;
2093 if ( $.inArray( state
, [ 'ready', 'error', 'missing' ] ) !== -1 ) {
2094 // Make sure pending modules depending on this one get executed if their
2095 // dependencies are now fulfilled!
2096 handlePending( module
);
2101 * Get the version of a module.
2103 * @param {string} module Name of module
2104 * @return {string|null} The version, or null if the module (or its version) is not
2107 getVersion: function ( module
) {
2108 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].version
=== undefined ) {
2111 return registry
[ module
].version
;
2115 * Get the state of a module.
2117 * @param {string} module Name of module
2118 * @return {string|null} The state, or null if the module (or its state) is not
2121 getState: function ( module
) {
2122 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].state
=== undefined ) {
2125 return registry
[ module
].state
;
2129 * Get the names of all registered modules.
2133 getModuleNames: function () {
2134 return $.map( registry
, function ( i
, key
) {
2140 * Get the exported value of a module.
2142 * Modules may provide this via their local `module.exports`.
2147 require: function ( moduleName
) {
2148 var state
= mw
.loader
.getState( moduleName
);
2150 // Only ready modules can be required
2151 if ( state
!== 'ready' ) {
2152 // Module may've forgotten to declare a dependency
2153 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2156 return registry
[ moduleName
].module
.exports
;
2160 * @inheritdoc mw.inspect#runReports
2163 inspect: function () {
2164 var args
= slice
.call( arguments
);
2165 mw
.loader
.using( 'mediawiki.inspect', function () {
2166 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2171 * On browsers that implement the localStorage API, the module store serves as a
2172 * smart complement to the browser cache. Unlike the browser cache, the module store
2173 * can slice a concatenated response from ResourceLoader into its constituent
2174 * modules and cache each of them separately, using each module's versioning scheme
2175 * to determine when the cache should be invalidated.
2178 * @class mw.loader.store
2181 // Whether the store is in use on this page.
2184 MODULE_SIZE_MAX
: 100 * 1000,
2186 // The contents of the store, mapping '[name]@[version]' keys
2187 // to module implementations.
2191 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2194 * Construct a JSON-serializable object representing the content of the store.
2196 * @return {Object} Module store contents.
2198 toJSON: function () {
2199 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2203 * Get the localStorage key for the entire module store. The key references
2204 * $wgDBname to prevent clashes between wikis which share a common host.
2206 * @return {string} localStorage item key
2208 getStoreKey: function () {
2209 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2213 * Get a key on which to vary the module cache.
2215 * @return {string} String of concatenated vary conditions.
2217 getVary: function () {
2219 mw
.config
.get( 'skin' ),
2220 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2221 mw
.config
.get( 'wgUserLanguage' )
2226 * Initialize the store.
2228 * Retrieves store from localStorage and (if successfully retrieved) decoding
2229 * the stored JSON value to a plain object.
2231 * The try / catch block is used for JSON & localStorage feature detection.
2232 * See the in-line documentation for Modernizr's localStorage feature detection
2233 * code for a full account of why we need a try / catch:
2234 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2239 if ( mw
.loader
.store
.enabled
!== null ) {
2245 // Disabled because localStorage quotas are tight and (in Firefox's case)
2246 // shared by multiple origins.
2247 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2248 /Firefox|Opera/.test( navigator
.userAgent
) ||
2250 // Disabled by configuration.
2251 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2253 // Clear any previous store to free up space. (T66721)
2254 mw
.loader
.store
.clear();
2255 mw
.loader
.store
.enabled
= false;
2258 if ( mw
.config
.get( 'debug' ) ) {
2259 // Disable module store in debug mode
2260 mw
.loader
.store
.enabled
= false;
2265 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2266 // If we get here, localStorage is available; mark enabled
2267 mw
.loader
.store
.enabled
= true;
2268 data
= JSON
.parse( raw
);
2269 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2270 mw
.loader
.store
.items
= data
.items
;
2274 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2277 if ( raw
=== undefined ) {
2278 // localStorage failed; disable store
2279 mw
.loader
.store
.enabled
= false;
2281 mw
.loader
.store
.update();
2286 * Retrieve a module from the store and update cache hit stats.
2288 * @param {string} module Module name
2289 * @return {string|boolean} Module implementation or false if unavailable
2291 get: function ( module
) {
2294 if ( !mw
.loader
.store
.enabled
) {
2298 key
= getModuleKey( module
);
2299 if ( key
in mw
.loader
.store
.items
) {
2300 mw
.loader
.store
.stats
.hits
++;
2301 return mw
.loader
.store
.items
[ key
];
2303 mw
.loader
.store
.stats
.misses
++;
2308 * Stringify a module and queue it for storage.
2310 * @param {string} module Module name
2311 * @param {Object} descriptor The module's descriptor as set in the registry
2313 set: function ( module
, descriptor
) {
2316 if ( !mw
.loader
.store
.enabled
) {
2320 key
= getModuleKey( module
);
2323 // Already stored a copy of this exact version
2324 key
in mw
.loader
.store
.items
||
2325 // Module failed to load
2326 descriptor
.state
!== 'ready' ||
2327 // Unversioned, private, or site-/user-specific
2328 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user' ] ) !== -1 ) ||
2329 // Partial descriptor
2330 // (e.g. skipped module, or style module with state=ready)
2331 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2332 descriptor
.messages
, descriptor
.templates
] ) !== -1
2340 JSON
.stringify( key
),
2341 typeof descriptor
.script
=== 'function' ?
2342 String( descriptor
.script
) :
2343 JSON
.stringify( descriptor
.script
),
2344 JSON
.stringify( descriptor
.style
),
2345 JSON
.stringify( descriptor
.messages
),
2346 JSON
.stringify( descriptor
.templates
)
2348 // Attempted workaround for a possible Opera bug (bug T59567).
2349 // This regex should never match under sane conditions.
2350 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2351 args
[ 1 ] = 'function' + args
[ 1 ];
2352 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2355 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2359 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2360 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2363 mw
.loader
.store
.items
[ key
] = src
;
2364 mw
.loader
.store
.update();
2368 * Iterate through the module store, removing any item that does not correspond
2369 * (in name and version) to an item in the module registry.
2371 prune: function () {
2374 if ( !mw
.loader
.store
.enabled
) {
2378 for ( key
in mw
.loader
.store
.items
) {
2379 module
= key
.slice( 0, key
.indexOf( '@' ) );
2380 if ( getModuleKey( module
) !== key
) {
2381 mw
.loader
.store
.stats
.expired
++;
2382 delete mw
.loader
.store
.items
[ key
];
2383 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2384 // This value predates the enforcement of a size limit on cached modules.
2385 delete mw
.loader
.store
.items
[ key
];
2391 * Clear the entire module store right now.
2393 clear: function () {
2394 mw
.loader
.store
.items
= {};
2396 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2397 } catch ( ignored
) {}
2401 * Sync in-memory store back to localStorage.
2403 * This function debounces updates. When called with a flush already pending,
2404 * the call is coalesced into the pending update. The call to
2405 * localStorage.setItem will be naturally deferred until the page is quiescent.
2407 * Because localStorage is shared by all pages from the same origin, if multiple
2408 * pages are loaded with different module sets, the possibility exists that
2409 * modules saved by one page will be clobbered by another. But the impact would
2410 * be minor and the problem would be corrected by subsequent page views.
2414 update
: ( function () {
2415 var hasPendingWrite
= false;
2417 function flushWrites() {
2419 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2423 mw
.loader
.store
.prune();
2424 key
= mw
.loader
.store
.getStoreKey();
2426 // Replacing the content of the module store might fail if the new
2427 // contents would exceed the browser's localStorage size limit. To
2428 // avoid clogging the browser with stale data, always remove the old
2429 // value before attempting to set the new one.
2430 localStorage
.removeItem( key
);
2431 data
= JSON
.stringify( mw
.loader
.store
);
2432 localStorage
.setItem( key
, data
);
2434 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2437 hasPendingWrite
= false;
2440 return function () {
2441 if ( !hasPendingWrite
) {
2442 hasPendingWrite
= true;
2443 mw
.requestIdleCallback( flushWrites
);
2452 * HTML construction helper functions
2459 * output = Html.element( 'div', {}, new Html.Raw(
2460 * Html.element( 'img', { src: '<' } )
2462 * mw.log( output ); // <div><img src="<"/></div>
2467 html
: ( function () {
2468 function escapeCallback( s
) {
2485 * Escape a string for HTML.
2487 * Converts special characters to HTML entities.
2489 * mw.html.escape( '< > \' & "' );
2490 * // Returns < > ' & "
2492 * @param {string} s The string to escape
2493 * @return {string} HTML
2495 escape: function ( s
) {
2496 return s
.replace( /['"<>&]/g, escapeCallback
);
2500 * Create an HTML element string, with safe escaping.
2502 * @param {string} name The tag name.
2503 * @param {Object} [attrs] An object with members mapping element names to values
2504 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2506 * - string: Text to be escaped.
2507 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2508 * - this.Raw: The raw value is directly included.
2509 * - this.Cdata: The raw value is directly included. An exception is
2510 * thrown if it contains any illegal ETAGO delimiter.
2511 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2512 * @return {string} HTML
2514 element: function ( name
, attrs
, contents
) {
2515 var v
, attrName
, s
= '<' + name
;
2518 for ( attrName
in attrs
) {
2519 v
= attrs
[ attrName
];
2520 // Convert name=true, to name=name
2524 } else if ( v
=== false ) {
2527 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2530 if ( contents
=== undefined || contents
=== null ) {
2537 switch ( typeof contents
) {
2540 s
+= this.escape( contents
);
2544 // Convert to string
2545 s
+= String( contents
);
2548 if ( contents
instanceof this.Raw
) {
2549 // Raw HTML inclusion
2550 s
+= contents
.value
;
2551 } else if ( contents
instanceof this.Cdata
) {
2553 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2554 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2556 s
+= contents
.value
;
2558 throw new Error( 'mw.html.element: Invalid type of contents' );
2561 s
+= '</' + name
+ '>';
2566 * Wrapper object for raw HTML passed to mw.html.element().
2568 * @class mw.html.Raw
2570 Raw: function ( value
) {
2575 * Wrapper object for CDATA element contents passed to mw.html.element()
2577 * @class mw.html.Cdata
2579 Cdata: function ( value
) {
2585 // Skeleton user object, extended by the 'mediawiki.user' module.
2592 * @property {mw.Map}
2596 * @property {mw.Map}
2601 // OOUI widgets specific to MediaWiki
2605 * Registry and firing of events.
2607 * MediaWiki has various interface components that are extended, enhanced
2608 * or manipulated in some other way by extensions, gadgets and even
2611 * This framework helps streamlining the timing of when these other
2612 * code paths fire their plugins (instead of using document-ready,
2613 * which can and should be limited to firing only once).
2615 * Features like navigating to other wiki pages, previewing an edit
2616 * and editing itself – without a refresh – can then retrigger these
2617 * hooks accordingly to ensure everything still works as expected.
2621 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2622 * mw.hook( 'wikipage.content' ).fire( $content );
2624 * Handlers can be added and fired for arbitrary event names at any time. The same
2625 * event can be fired multiple times. The last run of an event is memorized
2626 * (similar to `$(document).ready` and `$.Deferred().done`).
2627 * This means if an event is fired, and a handler added afterwards, the added
2628 * function will be fired right away with the last given event data.
2630 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2631 * Thus allowing flexible use and optimal maintainability and authority control.
2632 * You can pass around the `add` and/or `fire` method to another piece of code
2633 * without it having to know the event name (or `mw.hook` for that matter).
2635 * var h = mw.hook( 'bar.ready' );
2636 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2638 * Note: Events are documented with an underscore instead of a dot in the event
2639 * name due to jsduck not supporting dots in that position.
2643 hook
: ( function () {
2647 * Create an instance of mw.hook.
2651 * @param {string} name Name of hook.
2654 return function ( name
) {
2655 var list
= hasOwn
.call( lists
, name
) ?
2657 lists
[ name
] = $.Callbacks( 'memory' );
2661 * Register a hook handler
2663 * @param {...Function} handler Function to bind.
2669 * Unregister a hook handler
2671 * @param {...Function} handler Function to unbind.
2674 remove
: list
.remove
,
2679 * @param {...Mixed} data
2683 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2690 // Alias $j to jQuery for backwards compatibility
2691 // @deprecated since 1.23 Use $ or jQuery instead
2692 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2695 * Log a message to window.console, if possible.
2697 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2698 * also in production mode). Gets console references in each invocation instead of caching the
2699 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2702 * @param {string} topic Stream name passed by mw.track
2703 * @param {Object} data Data passed by mw.track
2704 * @param {Error} [data.exception]
2705 * @param {string} data.source Error source
2706 * @param {string} [data.module] Name of module which caused the error
2708 function logError( topic
, data
) {
2711 source
= data
.source
,
2712 module
= data
.module
,
2713 console
= window
.console
;
2715 if ( console
&& console
.log
) {
2716 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2718 msg
+= ' in module ' + module
;
2720 msg
+= ( e
? ':' : '.' );
2723 // If we have an exception object, log it to the error channel to trigger
2724 // proper stacktraces in browsers that support it. No fallback as we have
2725 // no browsers that don't support error(), but do support log().
2726 if ( e
&& console
.error
) {
2727 console
.error( String( e
), e
);
2732 // Subscribe to error streams
2733 mw
.trackSubscribe( 'resourceloader.exception', logError
);
2734 mw
.trackSubscribe( 'resourceloader.assert', logError
);
2737 * Fired when all modules associated with the page have finished loading.
2739 * @event resourceloader_loadEnd
2743 var loading
= $.grep( mw
.loader
.getModuleNames(), function ( module
) {
2744 return mw
.loader
.getState( module
) === 'loading';
2746 // We only need a callback, not any actual module. First try a single using()
2747 // for all loading modules. If one fails, fall back to tracking each module
2748 // separately via $.when(), this is expensive.
2749 loading
= mw
.loader
.using( loading
).then( null, function () {
2750 var all
= $.map( loading
, function ( module
) {
2751 return mw
.loader
.using( module
).then( null, function () {
2752 return $.Deferred().resolve();
2755 return $.when
.apply( $, all
);
2757 loading
.then( function () {
2758 mwPerformance
.mark( 'mwLoadEnd' );
2759 mw
.hook( 'resourceloader.loadEnd' ).fire();
2763 // Attach to window and globally alias
2764 window
.mw
= window
.mediaWiki
= mw
;