2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
10 /*jshint latedef:false */
16 hasOwn
= Object
.prototype.hasOwnProperty
,
17 slice
= Array
.prototype.slice
,
18 trackCallbacks
= $.Callbacks( 'memory' ),
23 * Create an object that can be read from or written to from methods that allow
24 * interaction both with single and multiple properties at once.
28 * var collection, query, results;
30 * // Create your address book
31 * collection = new mw.Map();
33 * // This data could be coming from an external source (eg. API/AJAX)
35 * 'John Doe': 'john@example.org',
36 * 'Jane Doe': 'jane@example.org',
37 * 'George van Halen': 'gvanhalen@example.org'
40 * wanted = ['John Doe', 'Jane Doe', 'Daniel Jackson'];
42 * // You can detect missing keys first
43 * if ( !collection.exists( wanted ) ) {
44 * // One or more are missing (in this case: "Daniel Jackson")
45 * mw.log( 'One or more names were not found in your address book' );
48 * // Or just let it give you what it can. Optionally fill in from a default.
49 * results = collection.get( wanted, 'nobody@example.com' );
50 * mw.log( results['Jane Doe'] ); // "jane@example.org"
51 * mw.log( results['Daniel Jackson'] ); // "nobody@example.com"
56 * @param {Object|boolean} [values] The value-baring object to be mapped. Defaults to an
58 * For backwards-compatibility with mw.config, this can also be `true` in which case values
59 * are copied to the Window object as global variables (T72470). Values are copied in
60 * one direction only. Changes to globals are not reflected in the map.
62 function Map( values
) {
63 if ( values
=== true ) {
66 // Override #set to also set the global variable
67 this.set = function ( selection
, value
) {
70 if ( $.isPlainObject( selection
) ) {
71 for ( s
in selection
) {
72 setGlobalMapValue( this, s
, selection
[ s
] );
76 if ( typeof selection
=== 'string' && arguments
.length
) {
77 setGlobalMapValue( this, selection
, value
);
86 this.values
= values
|| {};
90 * Alias property to the global object.
96 * @param {Mixed} value
98 function setGlobalMapValue( map
, key
, value
) {
99 map
.values
[ key
] = value
;
104 // Deprecation notice for mw.config globals (T58550, T72470)
105 map
=== mw
.config
&& 'Use mw.config instead.'
111 * Get the value of one or more keys.
113 * If called with no arguments, all values are returned.
115 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
116 * @param {Mixed} [fallback=null] Value for keys that don't exist.
117 * @return {Mixed|Object| null} If selection was a string, returns the value,
118 * If selection was an array, returns an object of key/values.
119 * If no selection is passed, the 'values' container is returned. (Beware that,
120 * as is the default in JavaScript, the object is returned by reference.)
122 get: function ( selection
, fallback
) {
124 // If we only do this in the `return` block, it'll fail for the
125 // call to get() from the mutli-selection block.
126 fallback
= arguments
.length
> 1 ? fallback
: null;
128 if ( $.isArray( selection
) ) {
129 selection
= slice
.call( selection
);
131 for ( i
= 0; i
< selection
.length
; i
++ ) {
132 results
[ selection
[ i
] ] = this.get( selection
[ i
], fallback
);
137 if ( typeof selection
=== 'string' ) {
138 if ( !hasOwn
.call( this.values
, selection
) ) {
141 return this.values
[ selection
];
144 if ( selection
=== undefined ) {
148 // Invalid selection key
153 * Set one or more key/value pairs.
155 * @param {string|Object} selection Key to set value for, or object mapping keys to values
156 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
157 * @return {boolean} True on success, false on failure
159 set: function ( selection
, value
) {
162 if ( $.isPlainObject( selection
) ) {
163 for ( s
in selection
) {
164 this.values
[ s
] = selection
[ s
];
168 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
169 this.values
[ selection
] = value
;
176 * Check if one or more keys exist.
178 * @param {Mixed} selection Key or array of keys to check
179 * @return {boolean} True if the key(s) exist
181 exists: function ( selection
) {
184 if ( $.isArray( selection
) ) {
185 for ( s
= 0; s
< selection
.length
; s
++ ) {
186 if ( typeof selection
[ s
] !== 'string' || !hasOwn
.call( this.values
, selection
[ s
] ) ) {
192 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
197 * Object constructor for messages.
199 * Similar to the Message class in MediaWiki PHP.
201 * Format defaults to 'text'.
207 * 'hello': 'Hello world',
208 * 'hello-user': 'Hello, $1!',
209 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
212 * obj = new mw.Message( mw.messages, 'hello' );
213 * mw.log( obj.text() );
216 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
217 * mw.log( obj.text() );
218 * // Hello, John Doe!
220 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
221 * mw.log( obj.text() );
222 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
224 * // Using mw.message shortcut
225 * obj = mw.message( 'hello-user', 'John Doe' );
226 * mw.log( obj.text() );
227 * // Hello, John Doe!
229 * // Using mw.msg shortcut
230 * str = mw.msg( 'hello-user', 'John Doe' );
232 * // Hello, John Doe!
234 * // Different formats
235 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
237 * obj.format = 'text';
238 * str = obj.toString();
243 * // Hello, John "Wiki" <3 Doe!
245 * mw.log( obj.escaped() );
246 * // Hello, John "Wiki" <3 Doe!
251 * @param {mw.Map} map Message store
252 * @param {string} key
253 * @param {Array} [parameters]
255 function Message( map
, key
, parameters
) {
256 this.format
= 'text';
259 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
263 Message
.prototype = {
265 * Get parsed contents of the message.
267 * The default parser does simple $N replacements and nothing else.
268 * This may be overridden to provide a more complex message parser.
269 * The primary override is in the mediawiki.jqueryMsg module.
271 * This function will not be called for nonexistent messages.
273 * @return {string} Parsed message
275 parser: function () {
276 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
280 * Add (does not replace) parameters for `N$` placeholder values.
282 * @param {Array} parameters
285 params: function ( parameters
) {
287 for ( i
= 0; i
< parameters
.length
; i
++ ) {
288 this.parameters
.push( parameters
[ i
] );
294 * Convert message object to its string form based on current format.
296 * @return {string} Message as a string in the current form, or `<key>` if key
299 toString: function () {
302 if ( !this.exists() ) {
303 // Use <key> as text if key does not exist
304 if ( this.format
=== 'escaped' || this.format
=== 'parse' ) {
305 // format 'escaped' and 'parse' need to have the brackets and key html escaped
306 return mw
.html
.escape( '<' + this.key
+ '>' );
308 return '<' + this.key
+ '>';
311 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
312 text
= this.parser();
315 if ( this.format
=== 'escaped' ) {
316 text
= this.parser();
317 text
= mw
.html
.escape( text
);
324 * Change format to 'parse' and convert message to string
326 * If jqueryMsg is loaded, this parses the message text from wikitext
327 * (where supported) to HTML
329 * Otherwise, it is equivalent to plain.
331 * @return {string} String form of parsed message
334 this.format
= 'parse';
335 return this.toString();
339 * Change format to 'plain' and convert message to string
341 * This substitutes parameters, but otherwise does not change the
344 * @return {string} String form of plain message
347 this.format
= 'plain';
348 return this.toString();
352 * Change format to 'text' and convert message to string
354 * If jqueryMsg is loaded, {{-transformation is done where supported
355 * (such as {{plural:}}, {{gender:}}, {{int:}}).
357 * Otherwise, it is equivalent to plain
359 * @return {string} String form of text message
362 this.format
= 'text';
363 return this.toString();
367 * Change the format to 'escaped' and convert message to string
369 * This is equivalent to using the 'text' format (see #text), then
370 * HTML-escaping the output.
372 * @return {string} String form of html escaped message
374 escaped: function () {
375 this.format
= 'escaped';
376 return this.toString();
380 * Check if a message exists
385 exists: function () {
386 return this.map
.exists( this.key
);
396 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
398 * On browsers that implement the Navigation Timing API, this function will produce floating-point
399 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
400 * it will fall back to using `Date`.
402 * @return {number} Current time
405 var perf
= window
.performance
,
406 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
407 return navStart
&& typeof perf
.now
=== 'function' ?
408 function () { return navStart
+ perf
.now(); } :
409 function () { return +new Date(); };
413 * Format a string. Replace $1, $2 ... $N with positional arguments.
415 * Used by Message#parser().
418 * @param {string} formatString Format string
419 * @param {...Mixed} parameters Values for $N replacements
420 * @return {string} Formatted string
422 format: function ( formatString
) {
423 var parameters
= slice
.call( arguments
, 1 );
424 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
425 var index
= parseInt( match
, 10 ) - 1;
426 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
431 * Track an analytic event.
433 * This method provides a generic means for MediaWiki JavaScript code to capture state
434 * information for analysis. Each logged event specifies a string topic name that describes
435 * the kind of event that it is. Topic names consist of dot-separated path components,
436 * arranged from most general to most specific. Each path component should have a clear and
437 * well-defined purpose.
439 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
440 * events that match their subcription, including those that fired before the handler was
443 * @param {string} topic Topic name
444 * @param {Object} [data] Data describing the event, encoded as an object
446 track: function ( topic
, data
) {
447 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
448 trackCallbacks
.fire( trackQueue
);
452 * Register a handler for subset of analytic events, specified by topic.
454 * Handlers will be called once for each tracked event, including any events that fired before the
455 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
456 * the exact time at which the event fired, a string 'topic' property naming the event, and a
457 * 'data' property which is an object of event-specific data. The event topic and event data are
458 * also passed to the callback as the first and second arguments, respectively.
460 * @param {string} topic Handle events whose name starts with this string prefix
461 * @param {Function} callback Handler to call for each matching tracked event
462 * @param {string} callback.topic
463 * @param {Object} [callback.data]
465 trackSubscribe: function ( topic
, callback
) {
467 function handler( trackQueue
) {
469 for ( ; seen
< trackQueue
.length
; seen
++ ) {
470 event
= trackQueue
[ seen
];
471 if ( event
.topic
.indexOf( topic
) === 0 ) {
472 callback
.call( event
, event
.topic
, event
.data
);
477 trackHandlers
.push( [ handler
, callback
] );
479 trackCallbacks
.add( handler
);
483 * Stop handling events for a particular handler
485 * @param {Function} callback
487 trackUnsubscribe: function ( callback
) {
488 trackHandlers
= $.grep( trackHandlers
, function ( fns
) {
489 if ( fns
[ 1 ] === callback
) {
490 trackCallbacks
.remove( fns
[ 0 ] );
491 // Ensure the tuple is removed to avoid holding on to closures
498 // Expose Map constructor
501 // Expose Message constructor
505 * Map of configuration values.
507 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
510 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
511 * global `window` object.
513 * @property {mw.Map} config
515 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
519 * Empty object for third-party libraries, for cases where you don't
520 * want to add a new global, or the global is bad and needs containment
528 * Access container for deprecated functionality that can be moved from
529 * from their legacy location and attached to this object (e.g. a global
530 * function that is deprecated and as stop-gap can be exposed through here).
532 * This was reserved for future use but never ended up being used.
534 * @deprecated since 1.22 Let deprecated identifiers keep their original name
535 * and use mw.log#deprecate to create an access container for tracking.
541 * Store for messages.
548 * Store for templates associated with a module.
552 templates
: new Map(),
555 * Get a message object.
557 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
560 * @param {string} key Key of message to get
561 * @param {...Mixed} parameters Values for $N replacements
562 * @return {mw.Message}
564 message: function ( key
) {
565 var parameters
= slice
.call( arguments
, 1 );
566 return new Message( mw
.messages
, key
, parameters
);
570 * Get a message string using the (default) 'text' format.
572 * Shortcut for `mw.message( key, parameters... ).text()`.
575 * @param {string} key Key of message to get
576 * @param {...Mixed} parameters Values for $N replacements
580 return mw
.message
.apply( mw
.message
, arguments
).toString();
584 * Dummy placeholder for {@link mw.log}
589 // Also update the restoration of methods in mediawiki.log.js
590 // when adding or removing methods here.
591 var log = function () {},
592 console
= window
.console
;
600 * Write a message to the console's warning channel.
601 * Actions not supported by the browser console are silently ignored.
603 * @param {...string} msg Messages to output to console
605 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
606 Function
.prototype.bind
.call( console
.warn
, console
) :
610 * Write a message to the console's error channel.
612 * Most browsers provide a stacktrace by default if the argument
613 * is a caught Error object.
616 * @param {Error|...string} msg Messages to output to console
618 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
619 Function
.prototype.bind
.call( console
.error
, console
) :
623 * Create a property in a host object that, when accessed, will produce
624 * a deprecation warning in the console with backtrace.
626 * @param {Object} obj Host object of deprecated property
627 * @param {string} key Name of property to create in `obj`
628 * @param {Mixed} val The value this property should return when accessed
629 * @param {string} [msg] Optional text to include in the deprecation message
631 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
633 } : function ( obj
, key
, val
, msg
) {
634 msg
= 'Use of "' + key
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
635 Object
.defineProperty( obj
, key
, {
639 mw
.track( 'mw.deprecate', key
);
643 set: function ( newVal
) {
644 mw
.track( 'mw.deprecate', key
);
656 * Client for ResourceLoader server end point.
658 * This client is in charge of maintaining the module registry and state
659 * machine, initiating network (batch) requests for loading modules, as
660 * well as dependency resolution and execution of source code.
662 * For more information, refer to
663 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
668 loader
: ( function () {
671 * Fired via mw.track on various resource loading errors.
673 * @event resourceloader_exception
674 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
675 * object, but in theory module code could manually throw something else, and that
676 * might also end up here.
677 * @param {string} [module] Name of the module which caused the error. Omitted if the
678 * error is not module-related or the module cannot be easily identified due to
680 * @param {string} source Source of the error. Possible values:
682 * - style: stylesheet error (only affects old IE where a special style loading method
684 * - load-callback: exception thrown by user callback
685 * - module-execute: exception thrown by module code
686 * - store-eval: could not evaluate module code cached in localStorage
687 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
688 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
689 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
693 * Fired via mw.track on resource loading error conditions.
695 * @event resourceloader_assert
696 * @param {string} source Source of the error. Possible values:
698 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
699 * bug; see <https://phabricator.wikimedia.org/T59567> for details
703 * Mapping of registered modules.
705 * See #implement and #execute for exact details on support for script, style and messages.
711 * // From mw.loader.register()
712 * 'version': '########' (hash)
713 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
714 * 'group': 'somegroup', (or) null
715 * 'source': 'local', (or) 'anotherwiki'
716 * 'skip': 'return !!window.Example', (or) null
717 * 'module': export Object
719 * // Set from execute() or mw.loader.state()
720 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
722 * // Optionally added at run-time by mw.loader.implement()
724 * 'script': closure, array of urls, or string
725 * 'style': { ... } (see #execute)
726 * 'messages': { 'key': 'value', ... }
733 * The module is known to the system but not yet requested.
734 * Meta data is registered via mw.loader#register. Calls to that method are
735 * generated server-side by the startup module.
737 * The module is requested through mw.loader (either directly or as dependency of
738 * another module). The client will be fetching module contents from the server.
739 * The contents are then stashed in the registry via mw.loader#implement.
741 * The module has been requested from the server and stashed via mw.loader#implement.
742 * If the module has no more dependencies in-fight, the module will be executed
743 * right away. Otherwise execution is deferred, controlled via #handlePending.
745 * The module is being executed.
747 * The module has been successfully executed.
749 * The module (or one of its dependencies) produced an error during execution.
751 * The module was registered client-side and requested, but the server denied knowledge
752 * of the module's existence.
758 // Mapping of sources, keyed by source-id, values are strings.
763 // 'sourceId': 'http://example.org/w/load.php'
768 // List of modules which will be loaded as when ready
771 // Pending queueModuleScript() requests
772 handlingPendingRequests
= false,
773 pendingRequests
= [],
775 // List of modules to be loaded
779 * List of callback jobs waiting for modules to be ready.
781 * Jobs are created by #request() and run by #handlePending().
783 * Typically when a job is created for a module, the job's dependencies contain
784 * both the module being requested and all its recursive dependencies.
789 * 'dependencies': [ module names ],
790 * 'ready': Function callback
791 * 'error': Function callback
794 * @property {Object[]} jobs
802 // For addEmbeddedCSS()
804 cssBufferTimer
= null,
805 cssCallbacks
= $.Callbacks(),
806 isIEto9
= 'documentMode' in document
&& document
.documentMode
<= 9,
807 isIE9
= document
.documentMode
=== 9;
809 function getMarker() {
812 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
814 mw
.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
815 marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
822 * Create a new style element and add it to the DOM.
825 * @param {string} text CSS text
826 * @param {Node} [nextNode] The element where the style tag
827 * should be inserted before
828 * @return {HTMLElement} Reference to the created style element
830 function newStyleTag( text
, nextNode
) {
831 var s
= document
.createElement( 'style' );
833 // Must attach style element to the document before setting cssText (T35305)
834 if ( nextNode
&& nextNode
.parentNode
) {
835 nextNode
.parentNode
.insertBefore( s
, nextNode
);
837 document
.getElementsByTagName( 'head' )[ 0 ].appendChild( s
);
839 if ( s
.styleSheet
) {
841 // Old IE ignores appended text nodes, access stylesheet directly.
842 s
.styleSheet
.cssText
= text
;
844 // Standard behaviour
845 s
.appendChild( document
.createTextNode( text
) );
851 * Add a bit of CSS text to the current browser page.
853 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
854 * or create a new one based on whether the given `cssText` is safe for extension.
856 * @param {string} [cssText=cssBuffer] If called without cssText,
857 * the internal buffer will be inserted instead.
858 * @param {Function} [callback]
860 function addEmbeddedCSS( cssText
, callback
) {
861 var $style
, styleEl
, newCssText
;
863 function fireCallbacks() {
864 var oldCallbacks
= cssCallbacks
;
865 // Reset cssCallbacks variable so it's not polluted by any calls to
866 // addEmbeddedCSS() from one of the callbacks (T105973)
867 cssCallbacks
= $.Callbacks();
868 oldCallbacks
.fire().empty();
872 cssCallbacks
.add( callback
);
875 // Yield once before creating the <style> tag. This lets multiple stylesheets
876 // accumulate into one buffer, allowing us to reduce how often new stylesheets
877 // are inserted in the browser. Appending a stylesheet and waiting for the
878 // browser to repaint is fairly expensive. (T47810)
880 // Don't extend the buffer if the item needs its own stylesheet.
881 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
882 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
883 // Linebreak for somewhat distinguishable sections
884 cssBuffer
+= '\n' + cssText
;
885 // TODO: Using requestAnimationFrame would perform better by not injecting
886 // styles while the browser is busy painting.
887 if ( !cssBufferTimer
) {
888 cssBufferTimer
= setTimeout( function () {
889 // Support: Firefox < 13
890 // Firefox 12 has non-standard behaviour of passing a number
891 // as first argument to a setTimeout callback.
892 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
899 // This is a scheduled flush for the buffer
901 cssBufferTimer
= null;
906 // By default, always create a new <style>. Appending text to a <style> tag is
907 // is a performance anti-pattern as it requires CSS to be reparsed (T47810).
910 // Try to re-use existing <style> tags due to the IE stylesheet limit (T33676).
912 $style
= $( getMarker() ).prev();
913 // Verify that the element before the marker actually is a <style> tag created
914 // by mw.loader (not some other style tag, or e.g. a <meta> tag).
915 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) ) {
916 styleEl
= $style
[ 0 ];
918 if ( styleEl
.styleSheet
) {
921 // We can't do styleSheet.cssText += cssText in IE9 because it mangles cssText on
922 // write (removes @media queries). If we read it and used its value, we'd
923 // accidentally apply @media-specific styles to all media. (T108727)
925 newCssText
= $style
.data( 'ResourceLoaderDynamicStyleTag' ) + cssText
;
926 styleEl
.styleSheet
.cssText
= newCssText
;
927 $style
.data( 'ResourceLoaderDynamicStyleTag', newCssText
);
929 styleEl
.styleSheet
.cssText
+= cssText
;
932 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'stylesheet' } );
935 styleEl
.appendChild( document
.createTextNode( cssText
) );
940 // Else: No existing tag to reuse. Continue below and create the first one.
943 $style
= $( newStyleTag( cssText
, getMarker() ) );
947 $style
.data( 'ResourceLoaderDynamicStyleTag', cssText
);
949 $style
.data( 'ResourceLoaderDynamicStyleTag', true );
958 * @param {Array} modules List of module names
959 * @return {string} Hash of concatenated version hashes.
961 function getCombinedVersion( modules
) {
962 var hashes
= $.map( modules
, function ( module
) {
963 return registry
[ module
].version
;
965 // Trim for consistency with server-side ResourceLoader::makeHash. It also helps
966 // save precious space in the limited query string. Otherwise modules are more
967 // likely to require multiple HTTP requests.
968 return sha1( hashes
.join( '' ) ).slice( 0, 12 );
972 * Determine whether all dependencies are in state 'ready', which means we may
973 * execute the module or job now.
976 * @param {Array} modules Names of modules to be checked
977 * @return {boolean} True if all modules are in state 'ready', false otherwise
979 function allReady( modules
) {
981 for ( i
= 0; i
< modules
.length
; i
++ ) {
982 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
990 * Determine whether all dependencies are in state 'ready', which means we may
991 * execute the module or job now.
994 * @param {Array} modules Names of modules to be checked
995 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
997 function anyFailed( modules
) {
999 for ( i
= 0; i
< modules
.length
; i
++ ) {
1000 state
= mw
.loader
.getState( modules
[ i
] );
1001 if ( state
=== 'error' || state
=== 'missing' ) {
1009 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1010 * pending jobs and modules that depend upon this module. If the given module failed,
1011 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1012 * all jobs/modules now having their dependencies satisfied.
1014 * Jobs that depend on a failed module, will have their error callback ran (if any).
1017 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1019 function handlePending( module
) {
1020 var j
, job
, hasErrors
, m
, stateChange
;
1022 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1023 // If the current module failed, mark all dependent modules also as failed.
1024 // Iterate until steady-state to propagate the error state upwards in the
1027 stateChange
= false;
1028 for ( m
in registry
) {
1029 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1030 if ( anyFailed( registry
[ m
].dependencies
) ) {
1031 registry
[ m
].state
= 'error';
1036 } while ( stateChange
);
1039 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1040 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1041 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1042 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1043 // All dependencies satisfied, or some have errors
1045 jobs
.splice( j
, 1 );
1049 if ( $.isFunction( job
.error
) ) {
1050 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1053 if ( $.isFunction( job
.ready
) ) {
1058 // A user-defined callback raised an exception.
1059 // Swallow it to protect our state machine!
1060 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1065 if ( registry
[ module
].state
=== 'ready' ) {
1066 // The current module became 'ready'. Set it in the module store, and recursively execute all
1067 // dependent modules that are loaded and now have all dependencies satisfied.
1068 mw
.loader
.store
.set( module
, registry
[ module
] );
1069 for ( m
in registry
) {
1070 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1078 * Resolve dependencies and detect circular references.
1081 * @param {string} module Name of the top-level module whose dependencies shall be
1082 * resolved and sorted.
1083 * @param {Array} resolved Returns a topological sort of the given module and its
1084 * dependencies, such that later modules depend on earlier modules. The array
1085 * contains the module names. If the array contains already some module names,
1086 * this function appends its result to the pre-existing array.
1087 * @param {Object} [unresolved] Hash used to track the current dependency
1088 * chain; used to report loops in the dependency graph.
1089 * @throws {Error} If any unregistered module or a dependency loop is encountered
1091 function sortDependencies( module
, resolved
, unresolved
) {
1094 if ( !hasOwn
.call( registry
, module
) ) {
1095 throw new Error( 'Unknown dependency: ' + module
);
1098 if ( registry
[ module
].skip
!== null ) {
1099 /*jshint evil:true */
1100 skip
= new Function( registry
[ module
].skip
);
1101 registry
[ module
].skip
= null;
1103 registry
[ module
].skipped
= true;
1104 registry
[ module
].dependencies
= [];
1105 registry
[ module
].state
= 'ready';
1106 handlePending( module
);
1111 // Resolves dynamic loader function and replaces it with its own results
1112 if ( $.isFunction( registry
[ module
].dependencies
) ) {
1113 registry
[ module
].dependencies
= registry
[ module
].dependencies();
1114 // Ensures the module's dependencies are always in an array
1115 if ( typeof registry
[ module
].dependencies
!== 'object' ) {
1116 registry
[ module
].dependencies
= [ registry
[ module
].dependencies
];
1119 if ( $.inArray( module
, resolved
) !== -1 ) {
1120 // Module already resolved; nothing to do
1123 // Create unresolved if not passed in
1124 if ( !unresolved
) {
1127 // Tracks down dependencies
1128 deps
= registry
[ module
].dependencies
;
1129 for ( i
= 0; i
< deps
.length
; i
++ ) {
1130 if ( $.inArray( deps
[ i
], resolved
) === -1 ) {
1131 if ( unresolved
[ deps
[ i
] ] ) {
1132 throw new Error( mw
.format(
1133 'Circular reference detected: $1 -> $2',
1139 // Add to unresolved
1140 unresolved
[ module
] = true;
1141 sortDependencies( deps
[ i
], resolved
, unresolved
);
1144 resolved
.push( module
);
1148 * Get names of module that a module depends on, in their proper dependency order.
1151 * @param {string[]} modules Array of string module names
1152 * @return {Array} List of dependencies, including 'module'.
1154 function resolve( modules
) {
1156 $.each( modules
, function ( idx
, module
) {
1157 sortDependencies( module
, resolved
);
1163 * Load and execute a script.
1166 * @param {string} src URL to script, will be used as the src attribute in the script tag
1167 * @return {jQuery.Promise}
1169 function addScript( src
) {
1173 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1174 // XHR for a same domain request instead of <script>, which changes the request
1175 // headers (potentially missing a cache hit), and reduces caching in general
1176 // since browsers cache XHR much less (if at all). And XHR means we retreive
1177 // text, so we'd need to $.globalEval, which then messes up line numbers.
1184 * Queue the loading and execution of a script for a particular module.
1187 * @param {string} src URL of the script
1188 * @param {string} [moduleName] Name of currently executing module
1189 * @return {jQuery.Promise}
1191 function queueModuleScript( src
, moduleName
) {
1192 var r
= $.Deferred();
1194 pendingRequests
.push( function () {
1195 if ( moduleName
&& hasOwn
.call( registry
, moduleName
) ) {
1196 window
.require
= mw
.loader
.require
;
1197 window
.module
= registry
[ moduleName
].module
;
1199 addScript( src
).always( function () {
1200 // Clear environment
1201 delete window
.require
;
1202 delete window
.module
;
1205 // Start the next one (if any)
1206 if ( pendingRequests
[ 0 ] ) {
1207 pendingRequests
.shift()();
1209 handlingPendingRequests
= false;
1213 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1214 handlingPendingRequests
= true;
1215 pendingRequests
.shift()();
1221 * Utility function for execute()
1225 function addLink( media
, url
) {
1226 var el
= document
.createElement( 'link' );
1228 // Insert in document *before* setting href
1229 $( getMarker() ).before( el
);
1230 el
.rel
= 'stylesheet';
1231 if ( media
&& media
!== 'all' ) {
1234 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1235 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1240 * Executes a loaded module, making it ready to use
1243 * @param {string} module Module name to execute
1245 function execute( module
) {
1246 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1247 cssHandlesRegistered
= false;
1249 if ( !hasOwn
.call( registry
, module
) ) {
1250 throw new Error( 'Module has not been registered yet: ' + module
);
1252 if ( registry
[ module
].state
!== 'loaded' ) {
1253 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1256 registry
[ module
].state
= 'executing';
1258 runScript = function () {
1259 var script
, markModuleReady
, nestedAddScript
, legacyWait
,
1260 // Expand to include dependencies since we have to exclude both legacy modules
1261 // and their dependencies from the legacyWait (to prevent a circular dependency).
1262 legacyModules
= resolve( mw
.config
.get( 'wgResourceLoaderLegacyModules', [] ) );
1264 script
= registry
[ module
].script
;
1265 markModuleReady = function () {
1266 registry
[ module
].state
= 'ready';
1267 handlePending( module
);
1269 nestedAddScript = function ( arr
, callback
, i
) {
1270 // Recursively call queueModuleScript() in its own callback
1271 // for each element of arr.
1272 if ( i
>= arr
.length
) {
1273 // We're at the end of the array
1278 queueModuleScript( arr
[ i
], module
).always( function () {
1279 nestedAddScript( arr
, callback
, i
+ 1 );
1283 legacyWait
= ( $.inArray( module
, legacyModules
) !== -1 )
1284 ? $.Deferred().resolve()
1285 : mw
.loader
.using( legacyModules
);
1287 legacyWait
.always( function () {
1288 if ( $.isArray( script
) ) {
1289 nestedAddScript( script
, markModuleReady
, 0 );
1290 } else if ( $.isFunction( script
) ) {
1291 // Pass jQuery twice so that the signature of the closure which wraps
1292 // the script can bind both '$' and 'jQuery'.
1293 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1296 } else if ( typeof script
=== 'string' ) {
1297 // Site and user modules are legacy scripts that run in the global scope.
1298 // This is transported as a string instead of a function to avoid needing
1299 // to use string manipulation to undo the function wrapper.
1300 if ( module
=== 'user' ) {
1301 // Implicit dependency on the site module. Not real dependency because
1302 // it should run after 'site' regardless of whether it succeeds or fails.
1303 mw
.loader
.using( 'site' ).always( function () {
1304 $.globalEval( script
);
1308 $.globalEval( script
);
1312 // Module without script
1317 // This needs to NOT use mw.log because these errors are common in production mode
1318 // and not in debug mode, such as when a symbol that should be global isn't exported
1319 registry
[ module
].state
= 'error';
1320 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1321 handlePending( module
);
1325 // Add localizations to message system
1326 if ( registry
[ module
].messages
) {
1327 mw
.messages
.set( registry
[ module
].messages
);
1330 // Initialise templates
1331 if ( registry
[ module
].templates
) {
1332 mw
.templates
.set( module
, registry
[ module
].templates
);
1335 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1338 checkCssHandles = function () {
1339 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1340 // one of the cssHandles is fired while we're still creating more handles.
1341 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1343 runScript
= undefined; // Revoke
1346 cssHandle = function () {
1347 var check
= checkCssHandles
;
1349 return function () {
1353 check
= undefined; // Revoke
1359 // Process styles (see also mw.loader.implement)
1360 // * back-compat: { <media>: css }
1361 // * back-compat: { <media>: [url, ..] }
1362 // * { "css": [css, ..] }
1363 // * { "url": { <media>: [url, ..] } }
1364 if ( registry
[ module
].style
) {
1365 for ( key
in registry
[ module
].style
) {
1366 value
= registry
[ module
].style
[ key
];
1369 if ( key
!== 'url' && key
!== 'css' ) {
1370 // Backwards compatibility, key is a media-type
1371 if ( typeof value
=== 'string' ) {
1372 // back-compat: { <media>: css }
1373 // Ignore 'media' because it isn't supported (nor was it used).
1374 // Strings are pre-wrapped in "@media". The media-type was just ""
1375 // (because it had to be set to something).
1376 // This is one of the reasons why this format is no longer used.
1377 addEmbeddedCSS( value
, cssHandle() );
1379 // back-compat: { <media>: [url, ..] }
1385 // Array of css strings in key 'css',
1386 // or back-compat array of urls from media-type
1387 if ( $.isArray( value
) ) {
1388 for ( i
= 0; i
< value
.length
; i
++ ) {
1389 if ( key
=== 'bc-url' ) {
1390 // back-compat: { <media>: [url, ..] }
1391 addLink( media
, value
[ i
] );
1392 } else if ( key
=== 'css' ) {
1393 // { "css": [css, ..] }
1394 addEmbeddedCSS( value
[ i
], cssHandle() );
1397 // Not an array, but a regular object
1398 // Array of urls inside media-type key
1399 } else if ( typeof value
=== 'object' ) {
1400 // { "url": { <media>: [url, ..] } }
1401 for ( media
in value
) {
1402 urls
= value
[ media
];
1403 for ( i
= 0; i
< urls
.length
; i
++ ) {
1404 addLink( media
, urls
[ i
] );
1412 cssHandlesRegistered
= true;
1417 * Adds all dependencies to the queue with optional callbacks to be run
1418 * when the dependencies are ready or fail
1421 * @param {string|string[]} dependencies Module name or array of string module names
1422 * @param {Function} [ready] Callback to execute when all dependencies are ready
1423 * @param {Function} [error] Callback to execute when any dependency fails
1425 function request( dependencies
, ready
, error
) {
1426 // Allow calling by single module name
1427 if ( typeof dependencies
=== 'string' ) {
1428 dependencies
= [ dependencies
];
1431 // Add ready and error callbacks if they were given
1432 if ( ready
!== undefined || error
!== undefined ) {
1434 // Narrow down the list to modules that are worth waiting for
1435 dependencies
: $.grep( dependencies
, function ( module
) {
1436 var state
= mw
.loader
.getState( module
);
1437 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1444 $.each( dependencies
, function ( idx
, module
) {
1445 var state
= mw
.loader
.getState( module
);
1446 // Only queue modules that are still in the initial 'registered' state
1447 // (not ones already loading, ready or error).
1448 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1449 // Private modules must be embedded in the page. Don't bother queuing
1450 // these as the server will deny them anyway (T101806).
1451 if ( registry
[ module
].group
=== 'private' ) {
1452 registry
[ module
].state
= 'error';
1453 handlePending( module
);
1456 queue
.push( module
);
1463 function sortQuery( o
) {
1469 if ( hasOwn
.call( o
, key
) ) {
1474 for ( key
= 0; key
< a
.length
; key
++ ) {
1475 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1481 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1482 * to a query string of the form foo.bar,baz|bar.baz,quux
1486 function buildModulesString( moduleMap
) {
1490 for ( prefix
in moduleMap
) {
1491 p
= prefix
=== '' ? '' : prefix
+ '.';
1492 arr
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1494 return arr
.join( '|' );
1498 * Load modules from load.php
1501 * @param {Object} moduleMap Module map, see #buildModulesString
1502 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1503 * @param {string} sourceLoadScript URL of load.php
1505 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
1506 var request
= $.extend(
1507 { modules
: buildModulesString( moduleMap
) },
1510 request
= sortQuery( request
);
1511 addScript( sourceLoadScript
+ '?' + $.param( request
) );
1515 * Resolve indexed dependencies.
1517 * ResourceLoader uses an optimization to save space which replaces module names in
1518 * dependency lists with the index of that module within the array of module
1519 * registration data if it exists. The benefit is a significant reduction in the data
1520 * size of the startup module. This function changes those dependency lists back to
1521 * arrays of strings.
1523 * @param {Array} modules Modules array
1525 function resolveIndexedDependencies( modules
) {
1526 $.each( modules
, function ( idx
, module
) {
1527 if ( module
[ 2 ] ) {
1528 module
[ 2 ] = $.map( module
[ 2 ], function ( dep
) {
1529 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1535 /* Public Members */
1538 * The module registry is exposed as an aid for debugging and inspecting page
1539 * state; it is not a public interface for modifying the registry.
1545 moduleRegistry
: registry
,
1548 * @inheritdoc #newStyleTag
1551 addStyleTag
: newStyleTag
,
1554 * Batch-request queued dependencies from the server.
1557 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
1558 source
, concatSource
, origBatch
, group
, i
, modules
, sourceLoadScript
,
1559 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1560 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1562 // Build a list of request parameters common to all requests.
1564 skin
: mw
.config
.get( 'skin' ),
1565 lang
: mw
.config
.get( 'wgUserLanguage' ),
1566 debug
: mw
.config
.get( 'debug' )
1568 // Split module batch by source and by group.
1570 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1572 // Appends a list of modules from the queue to the batch
1573 for ( q
= 0; q
< queue
.length
; q
++ ) {
1574 // Only request modules which are registered
1575 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1576 // Prevent duplicate entries
1577 if ( $.inArray( queue
[ q
], batch
) === -1 ) {
1578 batch
.push( queue
[ q
] );
1579 // Mark registered modules as loading
1580 registry
[ queue
[ q
] ].state
= 'loading';
1585 mw
.loader
.store
.init();
1586 if ( mw
.loader
.store
.enabled
) {
1589 batch
= $.grep( batch
, function ( module
) {
1590 var source
= mw
.loader
.store
.get( module
);
1592 concatSource
.push( source
);
1598 $.globalEval( concatSource
.join( ';' ) );
1600 // Not good, the cached mw.loader.implement calls failed! This should
1601 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1602 // Depending on how corrupt the string is, it is likely that some
1603 // modules' implement() succeeded while the ones after the error will
1604 // never run and leave their modules in the 'loading' state forever.
1606 // Since this is an error not caused by an individual module but by
1607 // something that infected the implement call itself, don't take any
1608 // risks and clear everything in this cache.
1609 mw
.loader
.store
.clear();
1610 // Re-add the ones still pending back to the batch and let the server
1611 // repopulate these modules to the cache.
1612 // This means that at most one module will be useless (the one that had
1613 // the error) instead of all of them.
1614 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1615 origBatch
= $.grep( origBatch
, function ( module
) {
1616 return registry
[ module
].state
=== 'loading';
1618 batch
= batch
.concat( origBatch
);
1622 // Early exit if there's nothing to load...
1623 if ( !batch
.length
) {
1627 // The queue has been processed into the batch, clear up the queue.
1630 // Always order modules alphabetically to help reduce cache
1631 // misses for otherwise identical content.
1634 // Split batch by source and by group.
1635 for ( b
= 0; b
< batch
.length
; b
++ ) {
1636 bSource
= registry
[ batch
[ b
] ].source
;
1637 bGroup
= registry
[ batch
[ b
] ].group
;
1638 if ( !hasOwn
.call( splits
, bSource
) ) {
1639 splits
[ bSource
] = {};
1641 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1642 splits
[ bSource
][ bGroup
] = [];
1644 bSourceGroup
= splits
[ bSource
][ bGroup
];
1645 bSourceGroup
.push( batch
[ b
] );
1648 // Clear the batch - this MUST happen before we append any
1649 // script elements to the body or it's possible that a script
1650 // will be locally cached, instantly load, and work the batch
1651 // again, all before we've cleared it causing each request to
1652 // include modules which are already loaded.
1655 for ( source
in splits
) {
1657 sourceLoadScript
= sources
[ source
];
1659 for ( group
in splits
[ source
] ) {
1661 // Cache access to currently selected list of
1662 // modules for this group from this source.
1663 modules
= splits
[ source
][ group
];
1665 currReqBase
= $.extend( {
1666 version
: getCombinedVersion( modules
)
1668 // For user modules append a user name to the request.
1669 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1670 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1672 currReqBaseLength
= $.param( currReqBase
).length
;
1673 // We may need to split up the request to honor the query string length limit,
1674 // so build it piece by piece.
1675 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1677 moduleMap
= {}; // { prefix: [ suffixes ] }
1679 for ( i
= 0; i
< modules
.length
; i
++ ) {
1680 // Determine how many bytes this module would add to the query string
1681 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1683 // If lastDotIndex is -1, substr() returns an empty string
1684 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1685 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1687 bytesAdded
= hasOwn
.call( moduleMap
, prefix
)
1688 ? suffix
.length
+ 3 // '%2C'.length == 3
1689 : modules
[ i
].length
+ 3; // '%7C'.length == 3
1691 // If the request would become too long, create a new one,
1692 // but don't create empty requests
1693 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1694 // This request would become too long, create a new one
1695 // and fire off the old one
1696 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1698 l
= currReqBaseLength
+ 9;
1699 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1701 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1702 moduleMap
[ prefix
] = [];
1704 moduleMap
[ prefix
].push( suffix
);
1707 // If there's anything left in moduleMap, request that too
1708 if ( !$.isEmptyObject( moduleMap
) ) {
1709 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1716 * Register a source.
1718 * The #work() method will use this information to split up requests by source.
1720 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1722 * @param {string|Object} id Source ID, or object mapping ids to load urls
1723 * @param {string} loadUrl Url to a load.php end point
1724 * @throws {Error} If source id is already registered
1726 addSource: function ( id
, loadUrl
) {
1728 // Allow multiple additions
1729 if ( typeof id
=== 'object' ) {
1730 for ( source
in id
) {
1731 mw
.loader
.addSource( source
, id
[ source
] );
1736 if ( hasOwn
.call( sources
, id
) ) {
1737 throw new Error( 'source already registered: ' + id
);
1740 sources
[ id
] = loadUrl
;
1744 * Register a module, letting the system know about it and its properties.
1746 * The startup modules contain calls to this method.
1748 * When using multiple module registration by passing an array, dependencies that
1749 * are specified as references to modules within the array will be resolved before
1750 * the modules are registered.
1752 * @param {string|Array} module Module name or array of arrays, each containing
1753 * a list of arguments compatible with this method
1754 * @param {string|number} version Module version hash (falls backs to empty string)
1755 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1756 * @param {string|Array|Function} dependencies One string or array of strings of module
1757 * names on which this module depends, or a function that returns that array.
1758 * @param {string} [group=null] Group which the module is in
1759 * @param {string} [source='local'] Name of the source
1760 * @param {string} [skip=null] Script body of the skip function
1762 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1764 // Allow multiple registration
1765 if ( typeof module
=== 'object' ) {
1766 resolveIndexedDependencies( module
);
1767 for ( i
= 0; i
< module
.length
; i
++ ) {
1768 // module is an array of module names
1769 if ( typeof module
[ i
] === 'string' ) {
1770 mw
.loader
.register( module
[ i
] );
1771 // module is an array of arrays
1772 } else if ( typeof module
[ i
] === 'object' ) {
1773 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1779 if ( typeof module
!== 'string' ) {
1780 throw new Error( 'module must be a string, not a ' + typeof module
);
1782 if ( hasOwn
.call( registry
, module
) ) {
1783 throw new Error( 'module already registered: ' + module
);
1785 // List the module as registered
1786 registry
[ module
] = {
1787 // Exposed to execute() for mw.loader.implement() closures.
1788 // Import happens via require().
1792 version
: version
!== undefined ? String( version
) : '',
1794 group
: typeof group
=== 'string' ? group
: null,
1795 source
: typeof source
=== 'string' ? source
: 'local',
1796 state
: 'registered',
1797 skip
: typeof skip
=== 'string' ? skip
: null
1799 if ( typeof dependencies
=== 'string' ) {
1800 // Allow dependencies to be given as a single module name
1801 registry
[ module
].dependencies
= [ dependencies
];
1802 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1803 // Allow dependencies to be given as an array of module names
1804 // or a function which returns an array
1805 registry
[ module
].dependencies
= dependencies
;
1810 * Implement a module given the components that make up the module.
1812 * When #load or #using requests one or more modules, the server
1813 * response contain calls to this function.
1815 * @param {string} module Name of module
1816 * @param {Function|Array} [script] Function with module code or Array of URLs to
1817 * be used as the src attribute of a new `<script>` tag.
1818 * @param {Object} [style] Should follow one of the following patterns:
1820 * { "css": [css, ..] }
1821 * { "url": { <media>: [url, ..] } }
1823 * And for backwards compatibility (needs to be supported forever due to caching):
1826 * { <media>: [url, ..] }
1828 * The reason css strings are not concatenated anymore is bug 31676. We now check
1829 * whether it's safe to extend the stylesheet.
1831 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1832 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1834 implement: function ( module
, script
, style
, messages
, templates
) {
1836 if ( typeof module
!== 'string' ) {
1837 throw new Error( 'module must be of type string, not ' + typeof module
);
1839 if ( script
&& !$.isFunction( script
) && !$.isArray( script
) && typeof script
!== 'string' ) {
1840 throw new Error( 'script must be of type function, array, or script; not ' + typeof script
);
1842 if ( style
&& !$.isPlainObject( style
) ) {
1843 throw new Error( 'style must be of type object, not ' + typeof style
);
1845 if ( messages
&& !$.isPlainObject( messages
) ) {
1846 throw new Error( 'messages must be of type object, not a ' + typeof messages
);
1848 if ( templates
&& !$.isPlainObject( templates
) ) {
1849 throw new Error( 'templates must be of type object, not a ' + typeof templates
);
1851 // Automatically register module
1852 if ( !hasOwn
.call( registry
, module
) ) {
1853 mw
.loader
.register( module
);
1855 // Check for duplicate implementation
1856 if ( hasOwn
.call( registry
, module
) && registry
[ module
].script
!== undefined ) {
1857 throw new Error( 'module already implemented: ' + module
);
1859 // Attach components
1860 registry
[ module
].script
= script
|| null;
1861 registry
[ module
].style
= style
|| null;
1862 registry
[ module
].messages
= messages
|| null;
1863 registry
[ module
].templates
= templates
|| null;
1864 // The module may already have been marked as erroneous
1865 if ( $.inArray( registry
[ module
].state
, [ 'error', 'missing' ] ) === -1 ) {
1866 registry
[ module
].state
= 'loaded';
1867 if ( allReady( registry
[ module
].dependencies
) ) {
1874 * Execute a function as soon as one or more required modules are ready.
1876 * Example of inline dependency on OOjs:
1878 * mw.loader.using( 'oojs', function () {
1879 * OO.compare( [ 1 ], [ 1 ] );
1882 * @param {string|Array} dependencies Module name or array of modules names the callback
1883 * dependends on to be ready before executing
1884 * @param {Function} [ready] Callback to execute when all dependencies are ready
1885 * @param {Function} [error] Callback to execute if one or more dependencies failed
1886 * @return {jQuery.Promise}
1887 * @since 1.23 this returns a promise
1889 using: function ( dependencies
, ready
, error
) {
1890 var deferred
= $.Deferred();
1892 // Allow calling with a single dependency as a string
1893 if ( typeof dependencies
=== 'string' ) {
1894 dependencies
= [ dependencies
];
1895 } else if ( !$.isArray( dependencies
) ) {
1897 throw new Error( 'Dependencies must be a string or an array' );
1901 deferred
.done( ready
);
1904 deferred
.fail( error
);
1907 // Resolve entire dependency map
1908 dependencies
= resolve( dependencies
);
1909 if ( allReady( dependencies
) ) {
1910 // Run ready immediately
1912 } else if ( anyFailed( dependencies
) ) {
1913 // Execute error immediately if any dependencies have errors
1915 new Error( 'One or more dependencies failed to load' ),
1919 // Not all dependencies are ready: queue up a request
1920 request( dependencies
, deferred
.resolve
, deferred
.reject
);
1923 return deferred
.promise();
1927 * Load an external script or one or more modules.
1929 * @param {string|Array} modules Either the name of a module, array of modules,
1930 * or a URL of an external script or style
1931 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1932 * external script or style; acceptable values are "text/css" and
1933 * "text/javascript"; if no type is provided, text/javascript is assumed.
1935 load: function ( modules
, type
) {
1939 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1940 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1942 // Allow calling with a url or single dependency as a string
1943 if ( typeof modules
=== 'string' ) {
1944 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1945 if ( /^(https?:)?\/?\//.test( modules
) ) {
1946 if ( type
=== 'text/css' ) {
1948 // Use properties instead of attributes as IE throws security
1949 // warnings when inserting a <link> tag with a protocol-relative
1950 // URL set though attributes - when on HTTPS. See bug 41331.
1951 l
= document
.createElement( 'link' );
1952 l
.rel
= 'stylesheet';
1954 $( 'head' ).append( l
);
1957 if ( type
=== 'text/javascript' || type
=== undefined ) {
1958 addScript( modules
);
1962 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1964 // Called with single module
1965 modules
= [ modules
];
1968 // Filter out undefined modules, otherwise resolve() will throw
1969 // an exception for trying to load an undefined module.
1970 // Undefined modules are acceptable here in load(), because load() takes
1971 // an array of unrelated modules, whereas the modules passed to
1972 // using() are related and must all be loaded.
1973 filtered
= $.grep( modules
, function ( module
) {
1974 var state
= mw
.loader
.getState( module
);
1975 return state
!== null && state
!== 'error' && state
!== 'missing';
1978 if ( filtered
.length
=== 0 ) {
1981 // Resolve entire dependency map
1982 filtered
= resolve( filtered
);
1983 // If all modules are ready, or if any modules have errors, nothing to be done.
1984 if ( allReady( filtered
) || anyFailed( filtered
) ) {
1987 // Since some modules are not yet ready, queue up a request.
1988 request( filtered
, undefined, undefined );
1992 * Change the state of one or more modules.
1994 * @param {string|Object} module Module name or object of module name/state pairs
1995 * @param {string} state State name
1997 state: function ( module
, state
) {
2000 if ( typeof module
=== 'object' ) {
2001 for ( m
in module
) {
2002 mw
.loader
.state( m
, module
[ m
] );
2006 if ( !hasOwn
.call( registry
, module
) ) {
2007 mw
.loader
.register( module
);
2009 if ( $.inArray( state
, [ 'ready', 'error', 'missing' ] ) !== -1
2010 && registry
[ module
].state
!== state
) {
2011 // Make sure pending modules depending on this one get executed if their
2012 // dependencies are now fulfilled!
2013 registry
[ module
].state
= state
;
2014 handlePending( module
);
2016 registry
[ module
].state
= state
;
2021 * Get the version of a module.
2023 * @param {string} module Name of module
2024 * @return {string|null} The version, or null if the module (or its version) is not
2027 getVersion: function ( module
) {
2028 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].version
=== undefined ) {
2031 return registry
[ module
].version
;
2035 * Get the state of a module.
2037 * @param {string} module Name of module
2038 * @return {string|null} The state, or null if the module (or its state) is not
2041 getState: function ( module
) {
2042 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].state
=== undefined ) {
2045 return registry
[ module
].state
;
2049 * Get the names of all registered modules.
2053 getModuleNames: function () {
2054 return $.map( registry
, function ( i
, key
) {
2060 * Get the exported value of a module.
2062 * Module provide this value via their local `module.exports`.
2067 require: function ( moduleName
) {
2068 var state
= mw
.loader
.getState( moduleName
);
2070 // Only ready mudules can be required
2071 if ( state
!== 'ready' ) {
2072 // Module may've forgotten to declare a dependency
2073 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2076 return registry
[ moduleName
].module
.exports
;
2080 * @inheritdoc mw.inspect#runReports
2083 inspect: function () {
2084 var args
= slice
.call( arguments
);
2085 mw
.loader
.using( 'mediawiki.inspect', function () {
2086 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2091 * On browsers that implement the localStorage API, the module store serves as a
2092 * smart complement to the browser cache. Unlike the browser cache, the module store
2093 * can slice a concatenated response from ResourceLoader into its constituent
2094 * modules and cache each of them separately, using each module's versioning scheme
2095 * to determine when the cache should be invalidated.
2098 * @class mw.loader.store
2101 // Whether the store is in use on this page.
2104 MODULE_SIZE_MAX
: 100 * 1000,
2106 // The contents of the store, mapping '[module name]@[version]' keys
2107 // to module implementations.
2111 stats
: { hits
: 0, misses
: 0, expired
: 0 },
2114 * Construct a JSON-serializable object representing the content of the store.
2116 * @return {Object} Module store contents.
2118 toJSON: function () {
2119 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2123 * Get the localStorage key for the entire module store. The key references
2124 * $wgDBname to prevent clashes between wikis which share a common host.
2126 * @return {string} localStorage item key
2128 getStoreKey: function () {
2129 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2133 * Get a key on which to vary the module cache.
2135 * @return {string} String of concatenated vary conditions.
2137 getVary: function () {
2139 mw
.config
.get( 'skin' ),
2140 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2141 mw
.config
.get( 'wgUserLanguage' )
2146 * Get a key for a specific module. The key format is '[name]@[version]'.
2148 * @param {string} module Module name
2149 * @return {string|null} Module key or null if module does not exist
2151 getModuleKey: function ( module
) {
2152 return hasOwn
.call( registry
, module
) ?
2153 ( module
+ '@' + registry
[ module
].version
) : null;
2157 * Initialize the store.
2159 * Retrieves store from localStorage and (if successfully retrieved) decoding
2160 * the stored JSON value to a plain object.
2162 * The try / catch block is used for JSON & localStorage feature detection.
2163 * See the in-line documentation for Modernizr's localStorage feature detection
2164 * code for a full account of why we need a try / catch:
2165 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2170 if ( mw
.loader
.store
.enabled
!== null ) {
2176 // Disabled because localStorage quotas are tight and (in Firefox's case)
2177 // shared by multiple origins.
2178 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2179 /Firefox|Opera/.test( navigator
.userAgent
) ||
2181 // Disabled by configuration.
2182 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2184 // Clear any previous store to free up space. (T66721)
2185 mw
.loader
.store
.clear();
2186 mw
.loader
.store
.enabled
= false;
2189 if ( mw
.config
.get( 'debug' ) ) {
2190 // Disable module store in debug mode
2191 mw
.loader
.store
.enabled
= false;
2196 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2197 // If we get here, localStorage is available; mark enabled
2198 mw
.loader
.store
.enabled
= true;
2199 data
= JSON
.parse( raw
);
2200 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2201 mw
.loader
.store
.items
= data
.items
;
2205 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2208 if ( raw
=== undefined ) {
2209 // localStorage failed; disable store
2210 mw
.loader
.store
.enabled
= false;
2212 mw
.loader
.store
.update();
2217 * Retrieve a module from the store and update cache hit stats.
2219 * @param {string} module Module name
2220 * @return {string|boolean} Module implementation or false if unavailable
2222 get: function ( module
) {
2225 if ( !mw
.loader
.store
.enabled
) {
2229 key
= mw
.loader
.store
.getModuleKey( module
);
2230 if ( key
in mw
.loader
.store
.items
) {
2231 mw
.loader
.store
.stats
.hits
++;
2232 return mw
.loader
.store
.items
[ key
];
2234 mw
.loader
.store
.stats
.misses
++;
2239 * Stringify a module and queue it for storage.
2241 * @param {string} module Module name
2242 * @param {Object} descriptor The module's descriptor as set in the registry
2244 set: function ( module
, descriptor
) {
2247 if ( !mw
.loader
.store
.enabled
) {
2251 key
= mw
.loader
.store
.getModuleKey( module
);
2254 // Already stored a copy of this exact version
2255 key
in mw
.loader
.store
.items
||
2256 // Module failed to load
2257 descriptor
.state
!== 'ready' ||
2258 // Unversioned, private, or site-/user-specific
2259 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user' ] ) !== -1 ) ||
2260 // Partial descriptor
2261 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2262 descriptor
.messages
, descriptor
.templates
] ) !== -1
2270 JSON
.stringify( module
),
2271 typeof descriptor
.script
=== 'function' ?
2272 String( descriptor
.script
) :
2273 JSON
.stringify( descriptor
.script
),
2274 JSON
.stringify( descriptor
.style
),
2275 JSON
.stringify( descriptor
.messages
),
2276 JSON
.stringify( descriptor
.templates
)
2278 // Attempted workaround for a possible Opera bug (bug T59567).
2279 // This regex should never match under sane conditions.
2280 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2281 args
[ 1 ] = 'function' + args
[ 1 ];
2282 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2285 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2289 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2290 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2293 mw
.loader
.store
.items
[ key
] = src
;
2294 mw
.loader
.store
.update();
2298 * Iterate through the module store, removing any item that does not correspond
2299 * (in name and version) to an item in the module registry.
2301 prune: function () {
2304 if ( !mw
.loader
.store
.enabled
) {
2308 for ( key
in mw
.loader
.store
.items
) {
2309 module
= key
.slice( 0, key
.indexOf( '@' ) );
2310 if ( mw
.loader
.store
.getModuleKey( module
) !== key
) {
2311 mw
.loader
.store
.stats
.expired
++;
2312 delete mw
.loader
.store
.items
[ key
];
2313 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2314 // This value predates the enforcement of a size limit on cached modules.
2315 delete mw
.loader
.store
.items
[ key
];
2321 * Clear the entire module store right now.
2323 clear: function () {
2324 mw
.loader
.store
.items
= {};
2326 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2327 } catch ( ignored
) {}
2331 * Sync in-memory store back to localStorage.
2333 * This function debounces updates. When called with a flush already pending,
2334 * the call is coalesced into the pending update. The call to
2335 * localStorage.setItem will be naturally deferred until the page is quiescent.
2337 * Because localStorage is shared by all pages from the same origin, if multiple
2338 * pages are loaded with different module sets, the possibility exists that
2339 * modules saved by one page will be clobbered by another. But the impact would
2340 * be minor and the problem would be corrected by subsequent page views.
2344 update
: ( function () {
2345 var hasPendingWrite
= false;
2347 function flushWrites() {
2349 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2353 mw
.loader
.store
.prune();
2354 key
= mw
.loader
.store
.getStoreKey();
2356 // Replacing the content of the module store might fail if the new
2357 // contents would exceed the browser's localStorage size limit. To
2358 // avoid clogging the browser with stale data, always remove the old
2359 // value before attempting to set the new one.
2360 localStorage
.removeItem( key
);
2361 data
= JSON
.stringify( mw
.loader
.store
);
2362 localStorage
.setItem( key
, data
);
2364 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2367 hasPendingWrite
= false;
2370 return function () {
2371 if ( !hasPendingWrite
) {
2372 hasPendingWrite
= true;
2373 mw
.requestIdleCallback( flushWrites
);
2382 * HTML construction helper functions
2389 * output = Html.element( 'div', {}, new Html.Raw(
2390 * Html.element( 'img', { src: '<' } )
2392 * mw.log( output ); // <div><img src="<"/></div>
2397 html
: ( function () {
2398 function escapeCallback( s
) {
2415 * Escape a string for HTML.
2417 * Converts special characters to HTML entities.
2419 * mw.html.escape( '< > \' & "' );
2420 * // Returns < > ' & "
2422 * @param {string} s The string to escape
2423 * @return {string} HTML
2425 escape: function ( s
) {
2426 return s
.replace( /['"<>&]/g, escapeCallback
);
2430 * Create an HTML element string, with safe escaping.
2432 * @param {string} name The tag name.
2433 * @param {Object} [attrs] An object with members mapping element names to values
2434 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2436 * - string: Text to be escaped.
2437 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2438 * - this.Raw: The raw value is directly included.
2439 * - this.Cdata: The raw value is directly included. An exception is
2440 * thrown if it contains any illegal ETAGO delimiter.
2441 * See <http://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2442 * @return {string} HTML
2444 element: function ( name
, attrs
, contents
) {
2445 var v
, attrName
, s
= '<' + name
;
2448 for ( attrName
in attrs
) {
2449 v
= attrs
[ attrName
];
2450 // Convert name=true, to name=name
2454 } else if ( v
=== false ) {
2457 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2460 if ( contents
=== undefined || contents
=== null ) {
2467 switch ( typeof contents
) {
2470 s
+= this.escape( contents
);
2474 // Convert to string
2475 s
+= String( contents
);
2478 if ( contents
instanceof this.Raw
) {
2479 // Raw HTML inclusion
2480 s
+= contents
.value
;
2481 } else if ( contents
instanceof this.Cdata
) {
2483 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2484 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2486 s
+= contents
.value
;
2488 throw new Error( 'mw.html.element: Invalid type of contents' );
2491 s
+= '</' + name
+ '>';
2496 * Wrapper object for raw HTML passed to mw.html.element().
2498 * @class mw.html.Raw
2500 Raw: function ( value
) {
2505 * Wrapper object for CDATA element contents passed to mw.html.element()
2507 * @class mw.html.Cdata
2509 Cdata: function ( value
) {
2515 // Skeleton user object, extended by the 'mediawiki.user' module.
2522 * @property {mw.Map}
2526 * @property {mw.Map}
2531 // OOUI widgets specific to MediaWiki
2535 * Registry and firing of events.
2537 * MediaWiki has various interface components that are extended, enhanced
2538 * or manipulated in some other way by extensions, gadgets and even
2541 * This framework helps streamlining the timing of when these other
2542 * code paths fire their plugins (instead of using document-ready,
2543 * which can and should be limited to firing only once).
2545 * Features like navigating to other wiki pages, previewing an edit
2546 * and editing itself – without a refresh – can then retrigger these
2547 * hooks accordingly to ensure everything still works as expected.
2551 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2552 * mw.hook( 'wikipage.content' ).fire( $content );
2554 * Handlers can be added and fired for arbitrary event names at any time. The same
2555 * event can be fired multiple times. The last run of an event is memorized
2556 * (similar to `$(document).ready` and `$.Deferred().done`).
2557 * This means if an event is fired, and a handler added afterwards, the added
2558 * function will be fired right away with the last given event data.
2560 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2561 * Thus allowing flexible use and optimal maintainability and authority control.
2562 * You can pass around the `add` and/or `fire` method to another piece of code
2563 * without it having to know the event name (or `mw.hook` for that matter).
2565 * var h = mw.hook( 'bar.ready' );
2566 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2568 * Note: Events are documented with an underscore instead of a dot in the event
2569 * name due to jsduck not supporting dots in that position.
2573 hook
: ( function () {
2577 * Create an instance of mw.hook.
2581 * @param {string} name Name of hook.
2584 return function ( name
) {
2585 var list
= hasOwn
.call( lists
, name
) ?
2587 lists
[ name
] = $.Callbacks( 'memory' );
2591 * Register a hook handler
2593 * @param {...Function} handler Function to bind.
2599 * Unregister a hook handler
2601 * @param {...Function} handler Function to unbind.
2604 remove
: list
.remove
,
2609 * @param {...Mixed} data
2613 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2620 // Alias $j to jQuery for backwards compatibility
2621 // @deprecated since 1.23 Use $ or jQuery instead
2622 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2625 * Log a message to window.console, if possible.
2627 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2628 * also in production mode). Gets console references in each invocation instead of caching the
2629 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2633 * @param {string} topic Stream name passed by mw.track
2634 * @param {Object} data Data passed by mw.track
2635 * @param {Error} [data.exception]
2636 * @param {string} data.source Error source
2637 * @param {string} [data.module] Name of module which caused the error
2639 function log( topic
, data
) {
2642 source
= data
.source
,
2643 module
= data
.module
,
2644 console
= window
.console
;
2646 if ( console
&& console
.log
) {
2647 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2649 msg
+= ' in module ' + module
;
2651 msg
+= ( e
? ':' : '.' );
2654 // If we have an exception object, log it to the error channel to trigger
2655 // proper stacktraces in browsers that support it. No fallback as we have
2656 // no browsers that don't support error(), but do support log().
2657 if ( e
&& console
.error
) {
2658 console
.error( String( e
), e
);
2663 // Subscribe to error streams
2664 mw
.trackSubscribe( 'resourceloader.exception', log
);
2665 mw
.trackSubscribe( 'resourceloader.assert', log
);
2668 * Fired when all modules associated with the page have finished loading.
2670 * @event resourceloader_loadEnd
2674 var loading
= $.grep( mw
.loader
.getModuleNames(), function ( module
) {
2675 return mw
.loader
.getState( module
) === 'loading';
2677 // In order to use jQuery.when (which stops early if one of the promises got rejected)
2678 // cast any loading failures into successes. We only need a callback, not the module.
2679 loading
= $.map( loading
, function ( module
) {
2680 return mw
.loader
.using( module
).then( null, function () {
2681 return $.Deferred().resolve();
2684 $.when
.apply( $, loading
).then( function () {
2685 mwPerformance
.mark( 'mwLoadEnd' );
2686 mw
.hook( 'resourceloader.loadEnd' ).fire();
2690 // Attach to window and globally alias
2691 window
.mw
= window
.mediaWiki
= mw
;