2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
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 /* eslint-disable no-bitwise */
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 ) {
49 /* eslint-enable no-bitwise */
52 function defineFallbacks() {
53 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
54 StringSet
= window
.Set
|| ( function () {
59 function StringSet() {
62 StringSet
.prototype.add = function ( value
) {
63 this.set[ value
] = true;
65 StringSet
.prototype.has = function ( value
) {
66 return hasOwn
.call( this.set, value
);
73 * Alias property to the global object.
80 * @param {Mixed} value
82 function setGlobalMapValue( map
, key
, value
) {
83 map
.values
[ key
] = value
;
88 // Deprecation notice for mw.config globals (T58550, T72470)
89 map
=== mw
.config
&& 'Use mw.config instead.'
94 * Create an object that can be read from or written to via methods that allow
95 * interaction both with single and multiple properties at once.
101 * @param {boolean} [global=false] Whether to synchronise =values to the global
102 * window object (for backwards-compatibility with mw.config; T72470). Values are
103 * copied in one direction only. Changes to globals do not reflect in the map.
105 function Map( global
) {
107 if ( global
=== true ) {
108 // Override #set to also set the global variable
109 this.set = function ( selection
, value
) {
111 if ( arguments
.length
> 1 ) {
112 if ( typeof selection
!== 'string' ) {
115 setGlobalMapValue( this, selection
, value
);
118 if ( typeof selection
=== 'object' ) {
119 for ( s
in selection
) {
120 setGlobalMapValue( this, s
, selection
[ s
] );
133 * Get the value of one or more keys.
135 * If called with no arguments, all values are returned.
137 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
138 * @param {Mixed} [fallback=null] Value for keys that don't exist.
139 * @return {Mixed|Object|null} If selection was a string, returns the value,
140 * If selection was an array, returns an object of key/values.
141 * If no selection is passed, a new object with all key/values is returned.
143 get: function ( selection
, fallback
) {
145 fallback
= arguments
.length
> 1 ? fallback
: null;
147 if ( Array
.isArray( selection
) ) {
149 for ( i
= 0; i
< selection
.length
; i
++ ) {
150 if ( typeof selection
[ i
] === 'string' ) {
151 results
[ selection
[ i
] ] = hasOwn
.call( this.values
, selection
[ i
] ) ?
152 this.values
[ selection
[ i
] ] :
159 if ( typeof selection
=== 'string' ) {
160 return hasOwn
.call( this.values
, selection
) ?
161 this.values
[ selection
] :
165 if ( selection
=== undefined ) {
167 for ( i
in this.values
) {
168 results
[ i
] = this.values
[ i
];
173 // Invalid selection key
178 * Set one or more key/value pairs.
180 * @param {string|Object} selection Key to set value for, or object mapping keys to values
181 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
182 * @return {boolean} True on success, false on failure
184 set: function ( selection
, value
) {
186 // Use `arguments.length` because `undefined` is also a valid value.
187 if ( arguments
.length
> 1 ) {
188 if ( typeof selection
!== 'string' ) {
191 this.values
[ selection
] = value
;
194 if ( typeof selection
=== 'object' ) {
195 for ( s
in selection
) {
196 this.values
[ s
] = selection
[ s
];
204 * Check if one or more keys exist.
206 * @param {Mixed} selection Key or array of keys to check
207 * @return {boolean} True if the key(s) exist
209 exists: function ( selection
) {
211 if ( Array
.isArray( selection
) ) {
212 for ( i
= 0; i
< selection
.length
; i
++ ) {
213 if ( typeof selection
[ i
] !== 'string' || !hasOwn
.call( this.values
, selection
[ i
] ) ) {
219 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
225 /* eslint-disable no-console */
226 log
= ( function () {
228 * Write a verbose message to the browser's console in debug mode.
230 * This method is mainly intended for verbose logging. It is a no-op in production mode.
231 * In ResourceLoader debug mode, it will use the browser's console if available, with
232 * fallback to creating a console interface in the DOM and logging messages there.
234 * See {@link mw.log} for other logging methods.
237 * @param {...string} msg Messages to output to console.
239 var log = function () {},
240 console
= window
.console
;
242 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
243 // when adding or removing mw.log methods below!
246 * Collection of methods to help log messages to the console.
253 * Write a message to the browser console's warning channel.
255 * This method is a no-op in browsers that don't implement the Console API.
257 * @param {...string} msg Messages to output to console
259 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
260 Function
.prototype.bind
.call( console
.warn
, console
) :
264 * Write a message to the browser console's error channel.
266 * Most browsers also print a stacktrace when calling this method if the
267 * argument is an Error object.
269 * This method is a no-op in browsers that don't implement the Console API.
272 * @param {Error|...string} msg Messages to output to console
274 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
275 Function
.prototype.bind
.call( console
.error
, console
) :
279 * Create a property on a host object that, when accessed, will produce
280 * a deprecation warning in the console.
282 * @param {Object} obj Host object of deprecated property
283 * @param {string} key Name of property to create in `obj`
284 * @param {Mixed} val The value this property should return when accessed
285 * @param {string} [msg] Optional text to include in the deprecation message
286 * @param {string} [logName=key] Optional custom name for the feature.
287 * This is used instead of `key` in the message and `mw.deprecate` tracking.
289 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
291 } : function ( obj
, key
, val
, msg
, logName
) {
292 var logged
= new StringSet();
293 logName
= logName
|| key
;
294 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
295 function uniqueTrace() {
296 var trace
= new Error().stack
;
297 if ( logged
.has( trace
) ) {
303 // Support: Safari 5.0
304 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
305 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
307 Object
.defineProperty( obj
, key
, {
311 if ( uniqueTrace() ) {
312 mw
.track( 'mw.deprecate', logName
);
317 set: function ( newVal
) {
318 if ( uniqueTrace() ) {
319 mw
.track( 'mw.deprecate', logName
);
332 /* eslint-enable no-console */
338 redefineFallbacksForTest: function () {
339 if ( !window
.QUnit
) {
340 throw new Error( 'Reset not allowed outside unit tests' );
346 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
348 * On browsers that implement the Navigation Timing API, this function will produce floating-point
349 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
350 * it will fall back to using `Date`.
352 * @return {number} Current time
355 var perf
= window
.performance
,
356 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
357 return navStart
&& typeof perf
.now
=== 'function' ?
358 function () { return navStart
+ perf
.now(); } :
359 function () { return Date
.now(); };
363 * Track an analytic event.
365 * This method provides a generic means for MediaWiki JavaScript code to capture state
366 * information for analysis. Each logged event specifies a string topic name that describes
367 * the kind of event that it is. Topic names consist of dot-separated path components,
368 * arranged from most general to most specific. Each path component should have a clear and
369 * well-defined purpose.
371 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
372 * events that match their subcription, including those that fired before the handler was
375 * @param {string} topic Topic name
376 * @param {Object} [data] Data describing the event, encoded as an object
378 track: function ( topic
, data
) {
379 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
380 trackCallbacks
.fire( trackQueue
);
384 * Register a handler for subset of analytic events, specified by topic.
386 * Handlers will be called once for each tracked event, including any events that fired before the
387 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
388 * the exact time at which the event fired, a string 'topic' property naming the event, and a
389 * 'data' property which is an object of event-specific data. The event topic and event data are
390 * also passed to the callback as the first and second arguments, respectively.
392 * @param {string} topic Handle events whose name starts with this string prefix
393 * @param {Function} callback Handler to call for each matching tracked event
394 * @param {string} callback.topic
395 * @param {Object} [callback.data]
397 trackSubscribe: function ( topic
, callback
) {
399 function handler( trackQueue
) {
401 for ( ; seen
< trackQueue
.length
; seen
++ ) {
402 event
= trackQueue
[ seen
];
403 if ( event
.topic
.indexOf( topic
) === 0 ) {
404 callback
.call( event
, event
.topic
, event
.data
);
409 trackHandlers
.push( [ handler
, callback
] );
411 trackCallbacks
.add( handler
);
415 * Stop handling events for a particular handler
417 * @param {Function} callback
419 trackUnsubscribe: function ( callback
) {
420 trackHandlers
= trackHandlers
.filter( function ( fns
) {
421 if ( fns
[ 1 ] === callback
) {
422 trackCallbacks
.remove( fns
[ 0 ] );
423 // Ensure the tuple is removed to avoid holding on to closures
430 // Expose Map constructor
434 * Map of configuration values.
436 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
439 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
440 * global `window` object.
442 * @property {mw.Map} config
444 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
448 * Empty object for third-party libraries, for cases where you don't
449 * want to add a new global, or the global is bad and needs containment
457 * Access container for deprecated functionality that can be moved from
458 * from their legacy location and attached to this object (e.g. a global
459 * function that is deprecated and as stop-gap can be exposed through here).
461 * This was reserved for future use but never ended up being used.
463 * @deprecated since 1.22 Let deprecated identifiers keep their original name
464 * and use mw.log#deprecate to create an access container for tracking.
470 * Store for messages.
477 * Store for templates associated with a module.
481 templates
: new Map(),
487 * Client for ResourceLoader server end point.
489 * This client is in charge of maintaining the module registry and state
490 * machine, initiating network (batch) requests for loading modules, as
491 * well as dependency resolution and execution of source code.
493 * For more information, refer to
494 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
499 loader
: ( function () {
502 * Fired via mw.track on various resource loading errors.
504 * @event resourceloader_exception
505 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
506 * object, but in theory module code could manually throw something else, and that
507 * might also end up here.
508 * @param {string} [module] Name of the module which caused the error. Omitted if the
509 * error is not module-related or the module cannot be easily identified due to
511 * @param {string} source Source of the error. Possible values:
513 * - style: stylesheet error (only affects old IE where a special style loading method
515 * - load-callback: exception thrown by user callback
516 * - module-execute: exception thrown by module code
517 * - resolve: failed to sort dependencies for a module in mw.loader.load
518 * - store-eval: could not evaluate module code cached in localStorage
519 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
520 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
521 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
525 * Fired via mw.track on resource loading error conditions.
527 * @event resourceloader_assert
528 * @param {string} source Source of the error. Possible values:
530 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
531 * bug; see <https://phabricator.wikimedia.org/T59567> for details
535 * Mapping of registered modules.
537 * See #implement and #execute for exact details on support for script, style and messages.
543 * // From mw.loader.register()
544 * 'version': '########' (hash)
545 * 'dependencies': ['required.foo', 'bar.also', ...]
546 * 'group': 'somegroup', (or) null
547 * 'source': 'local', (or) 'anotherwiki'
548 * 'skip': 'return !!window.Example', (or) null
549 * 'module': export Object
551 * // Set from execute() or mw.loader.state()
552 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
554 * // Optionally added at run-time by mw.loader.implement()
556 * 'script': closure, array of urls, or string
557 * 'style': { ... } (see #execute)
558 * 'messages': { 'key': 'value', ... }
565 * The module is known to the system but not yet required.
566 * Meta data is registered via mw.loader#register. Calls to that method are
567 * generated server-side by the startup module.
569 * The module was required through mw.loader (either directly or as dependency of
570 * another module). The client will fetch module contents from the server.
571 * The contents are then stashed in the registry via mw.loader#implement.
573 * The module has been loaded from the server and stashed via mw.loader#implement.
574 * If the module has no more dependencies in-flight, the module will be executed
575 * immediately. Otherwise execution is deferred, controlled via #handlePending.
577 * The module is being executed.
579 * The module has been successfully executed.
581 * The module (or one of its dependencies) produced an error during execution.
583 * The module was registered client-side and requested, but the server denied knowledge
584 * of the module's existence.
590 // Mapping of sources, keyed by source-id, values are strings.
595 // 'sourceId': 'http://example.org/w/load.php'
600 // For queueModuleScript()
601 handlingPendingRequests
= false,
602 pendingRequests
= [],
604 // List of modules to be loaded
608 * List of callback jobs waiting for modules to be ready.
610 * Jobs are created by #enqueue() and run by #handlePending().
612 * Typically when a job is created for a module, the job's dependencies contain
613 * both the required module and all its recursive dependencies.
618 * 'dependencies': [ module names ],
619 * 'ready': Function callback
620 * 'error': Function callback
623 * @property {Object[]} jobs
629 * For #addEmbeddedCSS() and #addLink()
632 * @property {HTMLElement|null} marker
634 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
636 // For addEmbeddedCSS()
638 cssBufferTimer
= null,
640 rAF
= window
.requestAnimationFrame
|| setTimeout
;
643 * Create a new style element and add it to the DOM.
646 * @param {string} text CSS text
647 * @param {Node|null} [nextNode] The element where the style tag
648 * should be inserted before
649 * @return {HTMLElement} Reference to the created style element
651 function newStyleTag( text
, nextNode
) {
652 var el
= document
.createElement( 'style' );
653 el
.appendChild( document
.createTextNode( text
) );
654 if ( nextNode
&& nextNode
.parentNode
) {
655 nextNode
.parentNode
.insertBefore( el
, nextNode
);
657 document
.head
.appendChild( el
);
663 * Add a bit of CSS text to the current browser page.
665 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
666 * or create a new one based on whether the given `cssText` is safe for extension.
669 * @param {string} [cssText=cssBuffer] If called without cssText,
670 * the internal buffer will be inserted instead.
671 * @param {Function} [callback]
673 function addEmbeddedCSS( cssText
, callback
) {
674 function fireCallbacks() {
676 oldCallbacks
= cssCallbacks
;
677 // Reset cssCallbacks variable so it's not polluted by any calls to
678 // addEmbeddedCSS() from one of the callbacks (T105973)
680 for ( i
= 0; i
< oldCallbacks
.length
; i
++ ) {
686 cssCallbacks
.push( callback
);
689 // Yield once before creating the <style> tag. This lets multiple stylesheets
690 // accumulate into one buffer, allowing us to reduce how often new stylesheets
691 // are inserted in the browser. Appending a stylesheet and waiting for the
692 // browser to repaint is fairly expensive. (T47810)
694 // Don't extend the buffer if the item needs its own stylesheet.
695 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
696 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
697 // Linebreak for somewhat distinguishable sections
698 cssBuffer
+= '\n' + cssText
;
699 if ( !cssBufferTimer
) {
700 cssBufferTimer
= rAF( function () {
701 // Wrap in anonymous function that takes no arguments
702 // Support: Firefox < 13
703 // Firefox 12 has non-standard behaviour of passing a number
704 // as first argument to a setTimeout callback.
705 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
712 // This is a scheduled flush for the buffer
714 cssBufferTimer
= null;
719 newStyleTag( cssText
, marker
);
726 * @param {Array} modules List of module names
727 * @return {string} Hash of concatenated version hashes.
729 function getCombinedVersion( modules
) {
730 var hashes
= modules
.map( function ( module
) {
731 return registry
[ module
].version
;
733 return fnv132( hashes
.join( '' ) );
737 * Determine whether all dependencies are in state 'ready', which means we may
738 * execute the module or job now.
741 * @param {Array} modules Names of modules to be checked
742 * @return {boolean} True if all modules are in state 'ready', false otherwise
744 function allReady( modules
) {
746 for ( i
= 0; i
< modules
.length
; i
++ ) {
747 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
755 * Determine whether all dependencies are in state 'ready', which means we may
756 * execute the module or job now.
759 * @param {Array} modules Names of modules to be checked
760 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
762 function anyFailed( modules
) {
764 for ( i
= 0; i
< modules
.length
; i
++ ) {
765 state
= mw
.loader
.getState( modules
[ i
] );
766 if ( state
=== 'error' || state
=== 'missing' ) {
774 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
775 * pending jobs and modules that depend upon this module. If the given module failed,
776 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
777 * all jobs/modules now having their dependencies satisfied.
779 * Jobs that depend on a failed module, will have their error callback ran (if any).
782 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
784 function handlePending( module
) {
785 var j
, job
, hasErrors
, m
, stateChange
;
787 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
788 // If the current module failed, mark all dependent modules also as failed.
789 // Iterate until steady-state to propagate the error state upwards in the
793 for ( m
in registry
) {
794 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
795 if ( anyFailed( registry
[ m
].dependencies
) ) {
796 registry
[ m
].state
= 'error';
801 } while ( stateChange
);
804 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
805 for ( j
= 0; j
< jobs
.length
; j
++ ) {
806 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
807 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
808 // All dependencies satisfied, or some have errors
814 if ( typeof job
.error
=== 'function' ) {
815 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
818 if ( typeof job
.ready
=== 'function' ) {
823 // A user-defined callback raised an exception.
824 // Swallow it to protect our state machine!
825 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
830 if ( registry
[ module
].state
=== 'ready' ) {
831 // The current module became 'ready'. Set it in the module store, and recursively execute all
832 // dependent modules that are loaded and now have all dependencies satisfied.
833 mw
.loader
.store
.set( module
, registry
[ module
] );
834 for ( m
in registry
) {
835 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
836 // eslint-disable-next-line no-use-before-define
844 * Resolve dependencies and detect circular references.
847 * @param {string} module Name of the top-level module whose dependencies shall be
848 * resolved and sorted.
849 * @param {Array} resolved Returns a topological sort of the given module and its
850 * dependencies, such that later modules depend on earlier modules. The array
851 * contains the module names. If the array contains already some module names,
852 * this function appends its result to the pre-existing array.
853 * @param {StringSet} [unresolved] Used to track the current dependency
854 * chain, and to report loops in the dependency graph.
855 * @throws {Error} If any unregistered module or a dependency loop is encountered
857 function sortDependencies( module
, resolved
, unresolved
) {
860 if ( !hasOwn
.call( registry
, module
) ) {
861 throw new Error( 'Unknown dependency: ' + module
);
864 if ( registry
[ module
].skip
!== null ) {
865 // eslint-disable-next-line no-new-func
866 skip
= new Function( registry
[ module
].skip
);
867 registry
[ module
].skip
= null;
869 registry
[ module
].skipped
= true;
870 registry
[ module
].dependencies
= [];
871 registry
[ module
].state
= 'ready';
872 handlePending( module
);
877 if ( resolved
.indexOf( module
) !== -1 ) {
878 // Module already resolved; nothing to do
881 // Create unresolved if not passed in
883 unresolved
= new StringSet();
885 // Tracks down dependencies
886 deps
= registry
[ module
].dependencies
;
887 for ( i
= 0; i
< deps
.length
; i
++ ) {
888 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
889 if ( unresolved
.has( deps
[ i
] ) ) {
891 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
895 unresolved
.add( module
);
896 sortDependencies( deps
[ i
], resolved
, unresolved
);
899 resolved
.push( module
);
903 * Get names of module that a module depends on, in their proper dependency order.
906 * @param {string[]} modules Array of string module names
907 * @return {Array} List of dependencies, including 'module'.
908 * @throws {Error} If an unregistered module or a dependency loop is encountered
910 function resolve( modules
) {
911 var i
, resolved
= [];
912 for ( i
= 0; i
< modules
.length
; i
++ ) {
913 sortDependencies( modules
[ i
], resolved
);
919 * Like #resolve(), except it will silently ignore modules that
920 * are missing or have missing dependencies.
923 * @param {string[]} modules Array of string module names
924 * @return {Array} List of dependencies.
926 function resolveStubbornly( modules
) {
927 var i
, saved
, resolved
= [];
928 for ( i
= 0; i
< modules
.length
; i
++ ) {
929 saved
= resolved
.slice();
931 sortDependencies( modules
[ i
], resolved
);
933 // This module is unknown or has unknown dependencies.
934 // Undo any incomplete resolutions made and keep going.
936 mw
.track( 'resourceloader.exception', {
946 * Load and execute a script.
949 * @param {string} src URL to script, will be used as the src attribute in the script tag
950 * @param {Function} [callback] Callback to run after request resolution
952 function addScript( src
, callback
) {
953 var script
= document
.createElement( 'script' );
955 script
.onload
= script
.onerror = function () {
956 if ( script
.parentNode
) {
957 script
.parentNode
.removeChild( script
);
965 document
.head
.appendChild( script
);
969 * Queue the loading and execution of a script for a particular module.
972 * @param {string} src URL of the script
973 * @param {string} moduleName Name of currently executing module
974 * @param {Function} callback Callback to run after addScript() resolution
976 function queueModuleScript( src
, moduleName
, callback
) {
977 pendingRequests
.push( function () {
978 if ( hasOwn
.call( registry
, moduleName
) ) {
979 // Emulate runScript() part of execute()
980 window
.require
= mw
.loader
.require
;
981 window
.module
= registry
[ moduleName
].module
;
983 addScript( src
, function () {
984 // 'module.exports' should not persist after the file is executed to
985 // avoid leakage to unrelated code. 'require' should be kept, however,
986 // as asynchronous access to 'require' is allowed and expected. (T144879)
987 delete window
.module
;
989 // Start the next one (if any)
990 if ( pendingRequests
[ 0 ] ) {
991 pendingRequests
.shift()();
993 handlingPendingRequests
= false;
997 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
998 handlingPendingRequests
= true;
999 pendingRequests
.shift()();
1004 * Utility function for execute()
1007 * @param {string} [media] Media attribute
1008 * @param {string} url URL
1010 function addLink( media
, url
) {
1011 var el
= document
.createElement( 'link' );
1013 el
.rel
= 'stylesheet';
1014 if ( media
&& media
!== 'all' ) {
1017 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1018 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1021 if ( marker
&& marker
.parentNode
) {
1022 marker
.parentNode
.insertBefore( el
, marker
);
1024 document
.head
.appendChild( el
);
1030 * @param {string} code JavaScript code
1032 function domEval( code
) {
1033 var script
= document
.createElement( 'script' );
1035 document
.head
.appendChild( script
);
1036 script
.parentNode
.removeChild( script
);
1040 * Executes a loaded module, making it ready to use
1043 * @param {string} module Module name to execute
1045 function execute( module
) {
1046 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1047 cssHandlesRegistered
= false;
1049 if ( !hasOwn
.call( registry
, module
) ) {
1050 throw new Error( 'Module has not been registered yet: ' + module
);
1052 if ( registry
[ module
].state
!== 'loaded' ) {
1053 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1056 registry
[ module
].state
= 'executing';
1058 runScript = function () {
1059 var script
, markModuleReady
, nestedAddScript
;
1061 script
= registry
[ module
].script
;
1062 markModuleReady = function () {
1063 registry
[ module
].state
= 'ready';
1064 handlePending( module
);
1066 nestedAddScript = function ( arr
, callback
, i
) {
1067 // Recursively call queueModuleScript() in its own callback
1068 // for each element of arr.
1069 if ( i
>= arr
.length
) {
1070 // We're at the end of the array
1075 queueModuleScript( arr
[ i
], module
, function () {
1076 nestedAddScript( arr
, callback
, i
+ 1 );
1081 if ( Array
.isArray( script
) ) {
1082 nestedAddScript( script
, markModuleReady
, 0 );
1083 } else if ( typeof script
=== 'function' ) {
1084 // Pass jQuery twice so that the signature of the closure which wraps
1085 // the script can bind both '$' and 'jQuery'.
1086 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1089 } else if ( typeof script
=== 'string' ) {
1090 // Site and user modules are legacy scripts that run in the global scope.
1091 // This is transported as a string instead of a function to avoid needing
1092 // to use string manipulation to undo the function wrapper.
1097 // Module without script
1101 // Use mw.track instead of mw.log because these errors are common in production mode
1102 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1103 registry
[ module
].state
= 'error';
1104 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1105 handlePending( module
);
1109 // Add localizations to message system
1110 if ( registry
[ module
].messages
) {
1111 mw
.messages
.set( registry
[ module
].messages
);
1114 // Initialise templates
1115 if ( registry
[ module
].templates
) {
1116 mw
.templates
.set( module
, registry
[ module
].templates
);
1119 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1122 checkCssHandles = function () {
1123 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1124 // one of the cssHandles is fired while we're still creating more handles.
1125 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1126 if ( module
=== 'user' ) {
1127 // Implicit dependency on the site module. Not real dependency because
1128 // it should run after 'site' regardless of whether it succeeds or fails.
1129 mw
.loader
.using( [ 'site' ] ).always( runScript
);
1133 runScript
= undefined; // Revoke
1136 cssHandle = function () {
1137 var check
= checkCssHandles
;
1139 return function () {
1143 check
= undefined; // Revoke
1149 // Process styles (see also mw.loader.implement)
1150 // * back-compat: { <media>: css }
1151 // * back-compat: { <media>: [url, ..] }
1152 // * { "css": [css, ..] }
1153 // * { "url": { <media>: [url, ..] } }
1154 if ( registry
[ module
].style
) {
1155 for ( key
in registry
[ module
].style
) {
1156 value
= registry
[ module
].style
[ key
];
1159 if ( key
!== 'url' && key
!== 'css' ) {
1160 // Backwards compatibility, key is a media-type
1161 if ( typeof value
=== 'string' ) {
1162 // back-compat: { <media>: css }
1163 // Ignore 'media' because it isn't supported (nor was it used).
1164 // Strings are pre-wrapped in "@media". The media-type was just ""
1165 // (because it had to be set to something).
1166 // This is one of the reasons why this format is no longer used.
1167 addEmbeddedCSS( value
, cssHandle() );
1169 // back-compat: { <media>: [url, ..] }
1175 // Array of css strings in key 'css',
1176 // or back-compat array of urls from media-type
1177 if ( Array
.isArray( value
) ) {
1178 for ( i
= 0; i
< value
.length
; i
++ ) {
1179 if ( key
=== 'bc-url' ) {
1180 // back-compat: { <media>: [url, ..] }
1181 addLink( media
, value
[ i
] );
1182 } else if ( key
=== 'css' ) {
1183 // { "css": [css, ..] }
1184 addEmbeddedCSS( value
[ i
], cssHandle() );
1187 // Not an array, but a regular object
1188 // Array of urls inside media-type key
1189 } else if ( typeof value
=== 'object' ) {
1190 // { "url": { <media>: [url, ..] } }
1191 for ( media
in value
) {
1192 urls
= value
[ media
];
1193 for ( i
= 0; i
< urls
.length
; i
++ ) {
1194 addLink( media
, urls
[ i
] );
1202 cssHandlesRegistered
= true;
1207 * Add one or more modules to the module load queue.
1212 * @param {string|string[]} dependencies Module name or array of string module names
1213 * @param {Function} [ready] Callback to execute when all dependencies are ready
1214 * @param {Function} [error] Callback to execute when any dependency fails
1216 function enqueue( dependencies
, ready
, error
) {
1217 // Allow calling by single module name
1218 if ( typeof dependencies
=== 'string' ) {
1219 dependencies
= [ dependencies
];
1222 // Add ready and error callbacks if they were given
1223 if ( ready
!== undefined || error
!== undefined ) {
1225 // Narrow down the list to modules that are worth waiting for
1226 dependencies
: dependencies
.filter( function ( module
) {
1227 var state
= mw
.loader
.getState( module
);
1228 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1235 dependencies
.forEach( function ( module
) {
1236 var state
= mw
.loader
.getState( module
);
1237 // Only queue modules that are still in the initial 'registered' state
1238 // (not ones already loading, ready or error).
1239 if ( state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1240 // Private modules must be embedded in the page. Don't bother queuing
1241 // these as the server will deny them anyway (T101806).
1242 if ( registry
[ module
].group
=== 'private' ) {
1243 registry
[ module
].state
= 'error';
1244 handlePending( module
);
1247 queue
.push( module
);
1254 function sortQuery( o
) {
1263 for ( key
= 0; key
< a
.length
; key
++ ) {
1264 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1270 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1271 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1273 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1274 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1276 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1277 * because its implementation needs to keep track of potential string size in order
1278 * to decide when to split the requests due to url size.
1281 * @param {Object} moduleMap Module map
1283 * @return {string} return.str Module query string
1284 * @return {Array} return.list List of module names in matching order
1286 function buildModulesString( moduleMap
) {
1291 function restore( suffix
) {
1295 for ( prefix
in moduleMap
) {
1296 p
= prefix
=== '' ? '' : prefix
+ '.';
1297 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1298 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1301 str
: str
.join( '|' ),
1307 * Resolve indexed dependencies.
1309 * ResourceLoader uses an optimization to save space which replaces module names in
1310 * dependency lists with the index of that module within the array of module
1311 * registration data if it exists. The benefit is a significant reduction in the data
1312 * size of the startup module. This function changes those dependency lists back to
1313 * arrays of strings.
1316 * @param {Array} modules Modules array
1318 function resolveIndexedDependencies( modules
) {
1320 function resolveIndex( dep
) {
1321 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1323 for ( i
= 0; i
< modules
.length
; i
++ ) {
1324 deps
= modules
[ i
][ 2 ];
1326 for ( j
= 0; j
< deps
.length
; j
++ ) {
1327 deps
[ j
] = resolveIndex( deps
[ j
] );
1335 * @param {Object} params Map of parameter names to values
1338 function makeQueryString( params
) {
1339 return Object
.keys( params
).map( function ( key
) {
1340 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1345 * Create network requests for a batch of modules.
1347 * This is an internal method for #work(). This must not be called directly
1348 * unless the modules are already registered, and no request is in progress,
1349 * and the module state has already been set to `loading`.
1352 * @param {string[]} batch
1354 function batchRequest( batch
) {
1355 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1356 source
, group
, i
, modules
, sourceLoadScript
,
1357 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1358 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1361 * Start the currently drafted request to the server.
1365 function doRequest() {
1366 // Optimisation: Inherit (Object.create), not copy ($.extend)
1367 var query
= Object
.create( currReqBase
),
1368 packed
= buildModulesString( moduleMap
);
1369 query
.modules
= packed
.str
;
1370 // The packing logic can change the effective order, even if the input was
1371 // sorted. As such, the call to getCombinedVersion() must use this
1372 // effective order, instead of currReqModules, as otherwise the combined
1373 // version will not match the hash expected by the server based on
1374 // combining versions from the module query string in-order. (T188076)
1375 query
.version
= getCombinedVersion( packed
.list
);
1376 query
= sortQuery( query
);
1377 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1380 if ( !batch
.length
) {
1384 // Always order modules alphabetically to help reduce cache
1385 // misses for otherwise identical content.
1388 // Query parameters common to all requests
1390 skin
: mw
.config
.get( 'skin' ),
1391 lang
: mw
.config
.get( 'wgUserLanguage' ),
1392 debug
: mw
.config
.get( 'debug' )
1394 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1396 // Split module list by source and by group.
1398 for ( b
= 0; b
< batch
.length
; b
++ ) {
1399 bSource
= registry
[ batch
[ b
] ].source
;
1400 bGroup
= registry
[ batch
[ b
] ].group
;
1401 if ( !hasOwn
.call( splits
, bSource
) ) {
1402 splits
[ bSource
] = {};
1404 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1405 splits
[ bSource
][ bGroup
] = [];
1407 bSourceGroup
= splits
[ bSource
][ bGroup
];
1408 bSourceGroup
.push( batch
[ b
] );
1411 for ( source
in splits
) {
1413 sourceLoadScript
= sources
[ source
];
1415 for ( group
in splits
[ source
] ) {
1417 // Cache access to currently selected list of
1418 // modules for this group from this source.
1419 modules
= splits
[ source
][ group
];
1421 // Query parameters common to requests for this module group
1422 // Optimisation: Inherit (Object.create), not copy ($.extend)
1423 currReqBase
= Object
.create( reqBase
);
1424 // User modules require a user name in the query string.
1425 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1426 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1429 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1430 // > '&modules='.length === 9
1431 // > '&version=1234567'.length === 16
1433 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1435 // We may need to split up the request to honor the query string length limit,
1436 // so build it piece by piece.
1437 l
= currReqBaseLength
;
1438 moduleMap
= {}; // { prefix: [ suffixes ] }
1439 currReqModules
= [];
1441 for ( i
= 0; i
< modules
.length
; i
++ ) {
1442 // Determine how many bytes this module would add to the query string
1443 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1444 // If lastDotIndex is -1, substr() returns an empty string
1445 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1446 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1447 bytesAdded
= hasOwn
.call( moduleMap
, prefix
) ?
1448 suffix
.length
+ 3 : // '%2C'.length == 3
1449 modules
[ i
].length
+ 3; // '%7C'.length == 3
1451 // If the url would become too long, create a new one, but don't create empty requests
1452 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1453 // Dispatch what we've got...
1455 // .. and start again.
1456 l
= currReqBaseLength
;
1458 currReqModules
= [];
1460 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1462 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1463 moduleMap
[ prefix
] = [];
1466 moduleMap
[ prefix
].push( suffix
);
1467 currReqModules
.push( modules
[ i
] );
1469 // If there's anything left in moduleMap, request that too
1470 if ( currReqModules
.length
) {
1479 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1480 * form of calls to mw.loader#implement().
1481 * @param {Function} cb Callback in case of failure
1482 * @param {Error} cb.err
1484 function asyncEval( implementations
, cb
) {
1485 if ( !implementations
.length
) {
1488 mw
.requestIdleCallback( function () {
1490 domEval( implementations
.join( ';' ) );
1498 * Make a versioned key for a specific module.
1501 * @param {string} module Module name
1502 * @return {string|null} Module key in format '`[name]@[version]`',
1503 * or null if the module does not exist
1505 function getModuleKey( module
) {
1506 return hasOwn
.call( registry
, module
) ?
1507 ( module
+ '@' + registry
[ module
].version
) : null;
1512 * @param {string} key Module name or '`[name]@[version]`'
1515 function splitModuleKey( key
) {
1516 var index
= key
.indexOf( '@' );
1517 if ( index
=== -1 ) {
1524 name
: key
.slice( 0, index
),
1525 version
: key
.slice( index
+ 1 )
1529 /* Public Members */
1532 * The module registry is exposed as an aid for debugging and inspecting page
1533 * state; it is not a public interface for modifying the registry.
1539 moduleRegistry
: registry
,
1542 * @inheritdoc #newStyleTag
1545 addStyleTag
: newStyleTag
,
1548 * Start loading of all queued module dependencies.
1553 var q
, batch
, implementations
, sourceModules
;
1557 // Appends a list of modules from the queue to the batch
1558 for ( q
= 0; q
< queue
.length
; q
++ ) {
1559 // Only load modules which are registered
1560 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1561 // Prevent duplicate entries
1562 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1563 batch
.push( queue
[ q
] );
1564 // Mark registered modules as loading
1565 registry
[ queue
[ q
] ].state
= 'loading';
1570 // Now that the queue has been processed into a batch, clear the queue.
1571 // This MUST happen before we initiate any eval or network request. Otherwise,
1572 // it is possible for a cached script to instantly trigger the same work queue
1573 // again; all before we've cleared it causing each request to include modules
1574 // which are already loaded.
1577 if ( !batch
.length
) {
1581 mw
.loader
.store
.init();
1582 if ( mw
.loader
.store
.enabled
) {
1583 implementations
= [];
1585 batch
= batch
.filter( function ( module
) {
1586 var implementation
= mw
.loader
.store
.get( module
);
1587 if ( implementation
) {
1588 implementations
.push( implementation
);
1589 sourceModules
.push( module
);
1594 asyncEval( implementations
, function ( err
) {
1596 // Not good, the cached mw.loader.implement calls failed! This should
1597 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1598 // Depending on how corrupt the string is, it is likely that some
1599 // modules' implement() succeeded while the ones after the error will
1600 // never run and leave their modules in the 'loading' state forever.
1601 mw
.loader
.store
.stats
.failed
++;
1603 // Since this is an error not caused by an individual module but by
1604 // something that infected the implement call itself, don't take any
1605 // risks and clear everything in this cache.
1606 mw
.loader
.store
.clear();
1608 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1609 // Re-add the failed ones that are still pending back to the batch
1610 failed
= sourceModules
.filter( function ( module
) {
1611 return registry
[ module
].state
=== 'loading';
1613 batchRequest( failed
);
1617 batchRequest( batch
);
1621 * Register a source.
1623 * The #work() method will use this information to split up requests by source.
1625 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1627 * @param {string|Object} id Source ID, or object mapping ids to load urls
1628 * @param {string} loadUrl Url to a load.php end point
1629 * @throws {Error} If source id is already registered
1631 addSource: function ( id
, loadUrl
) {
1633 // Allow multiple additions
1634 if ( typeof id
=== 'object' ) {
1635 for ( source
in id
) {
1636 mw
.loader
.addSource( source
, id
[ source
] );
1641 if ( hasOwn
.call( sources
, id
) ) {
1642 throw new Error( 'source already registered: ' + id
);
1645 sources
[ id
] = loadUrl
;
1649 * Register a module, letting the system know about it and its properties.
1651 * The startup modules contain calls to this method.
1653 * When using multiple module registration by passing an array, dependencies that
1654 * are specified as references to modules within the array will be resolved before
1655 * the modules are registered.
1657 * @param {string|Array} module Module name or array of arrays, each containing
1658 * a list of arguments compatible with this method
1659 * @param {string|number} version Module version hash (falls backs to empty string)
1660 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1661 * @param {string|Array} dependencies One string or array of strings of module
1662 * names on which this module depends.
1663 * @param {string} [group=null] Group which the module is in
1664 * @param {string} [source='local'] Name of the source
1665 * @param {string} [skip=null] Script body of the skip function
1667 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1669 // Allow multiple registration
1670 if ( typeof module
=== 'object' ) {
1671 resolveIndexedDependencies( module
);
1672 for ( i
= 0; i
< module
.length
; i
++ ) {
1673 // module is an array of module names
1674 if ( typeof module
[ i
] === 'string' ) {
1675 mw
.loader
.register( module
[ i
] );
1676 // module is an array of arrays
1677 } else if ( typeof module
[ i
] === 'object' ) {
1678 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1683 if ( hasOwn
.call( registry
, module
) ) {
1684 throw new Error( 'module already registered: ' + module
);
1686 if ( typeof dependencies
=== 'string' ) {
1687 // A single module name
1688 deps
= [ dependencies
];
1689 } else if ( typeof dependencies
=== 'object' ) {
1690 // Array of module names
1691 deps
= dependencies
;
1693 // List the module as registered
1694 registry
[ module
] = {
1695 // Exposed to execute() for mw.loader.implement() closures.
1696 // Import happens via require().
1700 version
: version
!== undefined ? String( version
) : '',
1701 dependencies
: deps
|| [],
1702 group
: typeof group
=== 'string' ? group
: null,
1703 source
: typeof source
=== 'string' ? source
: 'local',
1704 state
: 'registered',
1705 skip
: typeof skip
=== 'string' ? skip
: null
1710 * Implement a module given the components that make up the module.
1712 * When #load() or #using() requests one or more modules, the server
1713 * response contain calls to this function.
1715 * @param {string} module Name of module and current module version. Formatted
1716 * as '`[name]@[version]`". This version should match the requested version
1717 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1718 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1719 * @param {Function|Array|string} [script] Function with module code, list of URLs
1720 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1721 * @param {Object} [style] Should follow one of the following patterns:
1723 * { "css": [css, ..] }
1724 * { "url": { <media>: [url, ..] } }
1726 * And for backwards compatibility (needs to be supported forever due to caching):
1729 * { <media>: [url, ..] }
1731 * The reason css strings are not concatenated anymore is T33676. We now check
1732 * whether it's safe to extend the stylesheet.
1735 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1736 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1738 implement: function ( module
, script
, style
, messages
, templates
) {
1739 var split
= splitModuleKey( module
),
1741 version
= split
.version
;
1742 // Automatically register module
1743 if ( !hasOwn
.call( registry
, name
) ) {
1744 mw
.loader
.register( name
);
1746 // Check for duplicate implementation
1747 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1748 throw new Error( 'module already implemented: ' + name
);
1751 // Without this reset, if there is a version mismatch between the
1752 // requested and received module version, then mw.loader.store would
1753 // cache the response under the requested key. Thus poisoning the cache
1754 // indefinitely with a stale value. (T117587)
1755 registry
[ name
].version
= version
;
1757 // Attach components
1758 registry
[ name
].script
= script
|| null;
1759 registry
[ name
].style
= style
|| null;
1760 registry
[ name
].messages
= messages
|| null;
1761 registry
[ name
].templates
= templates
|| null;
1762 // The module may already have been marked as erroneous
1763 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1764 registry
[ name
].state
= 'loaded';
1765 if ( allReady( registry
[ name
].dependencies
) ) {
1772 * Execute a function as soon as one or more required modules are ready.
1774 * Example of inline dependency on OOjs:
1776 * mw.loader.using( 'oojs', function () {
1777 * OO.compare( [ 1 ], [ 1 ] );
1780 * Example of inline dependency obtained via `require()`:
1782 * mw.loader.using( [ 'mediawiki.util' ], function ( require ) {
1783 * var util = require( 'mediawiki.util' );
1786 * Since MediaWiki 1.23 this also returns a promise.
1788 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1790 * @param {string|Array} dependencies Module name or array of modules names the
1791 * callback depends on to be ready before executing
1792 * @param {Function} [ready] Callback to execute when all dependencies are ready
1793 * @param {Function} [error] Callback to execute if one or more dependencies failed
1794 * @return {jQuery.Promise} With a `require` function
1796 using: function ( dependencies
, ready
, error
) {
1797 var deferred
= $.Deferred();
1799 // Allow calling with a single dependency as a string
1800 if ( typeof dependencies
=== 'string' ) {
1801 dependencies
= [ dependencies
];
1805 deferred
.done( ready
);
1808 deferred
.fail( error
);
1812 // Resolve entire dependency map
1813 dependencies
= resolve( dependencies
);
1815 return deferred
.reject( e
).promise();
1817 if ( allReady( dependencies
) ) {
1818 // Run ready immediately
1819 deferred
.resolve( mw
.loader
.require
);
1820 } else if ( anyFailed( dependencies
) ) {
1821 // Execute error immediately if any dependencies have errors
1823 new Error( 'One or more dependencies failed to load' ),
1827 // Not all dependencies are ready, add to the load queue
1828 enqueue( dependencies
, function () {
1829 deferred
.resolve( mw
.loader
.require
);
1830 }, deferred
.reject
);
1833 return deferred
.promise();
1837 * Load an external script or one or more modules.
1839 * This method takes a list of unrelated modules. Use cases:
1841 * - A web page will be composed of many different widgets. These widgets independently
1842 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1843 * have problems, or are no longer known (e.g. cached HTML), the other modules
1844 * should still be loaded.
1845 * - This method is used for preloading, which must not throw. Later code that
1846 * calls #using() will handle the error.
1848 * @param {string|Array} modules Either the name of a module, array of modules,
1849 * or a URL of an external script or style
1850 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1851 * external script or style; acceptable values are "text/css" and
1852 * "text/javascript"; if no type is provided, text/javascript is assumed.
1854 load: function ( modules
, type
) {
1857 // Allow calling with a url or single dependency as a string
1858 if ( typeof modules
=== 'string' ) {
1859 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1860 if ( /^(https?:)?\/?\//.test( modules
) ) {
1861 if ( type
=== 'text/css' ) {
1862 l
= document
.createElement( 'link' );
1863 l
.rel
= 'stylesheet';
1865 document
.head
.appendChild( l
);
1868 if ( type
=== 'text/javascript' || type
=== undefined ) {
1869 addScript( modules
);
1873 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1875 // Called with single module
1876 modules
= [ modules
];
1879 // Filter out top-level modules that are unknown or failed to load before.
1880 filtered
= modules
.filter( function ( module
) {
1881 var state
= mw
.loader
.getState( module
);
1882 return state
!== 'error' && state
!== 'missing';
1884 // Resolve remaining list using the known dependency tree.
1885 // This also filters out modules with unknown dependencies. (T36853)
1886 filtered
= resolveStubbornly( filtered
);
1887 // If all modules are ready, or if any modules have errors, nothing to be done.
1888 if ( allReady( filtered
) || anyFailed( filtered
) ) {
1891 if ( filtered
.length
=== 0 ) {
1894 // Some modules are not yet ready, add to module load queue.
1895 enqueue( filtered
, undefined, undefined );
1899 * Change the state of one or more modules.
1901 * @param {string|Object} module Module name or object of module name/state pairs
1902 * @param {string} state State name
1904 state: function ( module
, state
) {
1907 if ( typeof module
=== 'object' ) {
1908 for ( m
in module
) {
1909 mw
.loader
.state( m
, module
[ m
] );
1913 if ( !hasOwn
.call( registry
, module
) ) {
1914 mw
.loader
.register( module
);
1916 registry
[ module
].state
= state
;
1917 if ( state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
1918 // Make sure pending modules depending on this one get executed if their
1919 // dependencies are now fulfilled!
1920 handlePending( module
);
1925 * Get the version of a module.
1927 * @param {string} module Name of module
1928 * @return {string|null} The version, or null if the module (or its version) is not
1931 getVersion: function ( module
) {
1932 return hasOwn
.call( registry
, module
) ? registry
[ module
].version
: null;
1936 * Get the state of a module.
1938 * @param {string} module Name of module
1939 * @return {string|null} The state, or null if the module (or its state) is not
1942 getState: function ( module
) {
1943 return hasOwn
.call( registry
, module
) ? registry
[ module
].state
: null;
1947 * Get the names of all registered modules.
1951 getModuleNames: function () {
1952 return Object
.keys( registry
);
1956 * Get the exported value of a module.
1958 * This static method is publicly exposed for debugging purposes
1959 * only and must not be used in production code. In production code,
1960 * please use the dynamically provided `require()` function instead.
1962 * In case of lazy-loaded modules via mw.loader#using(), the returned
1963 * Promise provides the function, see #using() for examples.
1967 * @param {string} moduleName Module name
1968 * @return {Mixed} Exported value
1970 require: function ( moduleName
) {
1971 var state
= mw
.loader
.getState( moduleName
);
1973 // Only ready modules can be required
1974 if ( state
!== 'ready' ) {
1975 // Module may've forgotten to declare a dependency
1976 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
1979 return registry
[ moduleName
].module
.exports
;
1983 * On browsers that implement the localStorage API, the module store serves as a
1984 * smart complement to the browser cache. Unlike the browser cache, the module store
1985 * can slice a concatenated response from ResourceLoader into its constituent
1986 * modules and cache each of them separately, using each module's versioning scheme
1987 * to determine when the cache should be invalidated.
1990 * @class mw.loader.store
1993 // Whether the store is in use on this page.
1996 // Modules whose string representation exceeds 100 kB are
1997 // ineligible for storage. See bug T66721.
1998 MODULE_SIZE_MAX
: 100 * 1000,
2000 // The contents of the store, mapping '[name]@[version]' keys
2001 // to module implementations.
2005 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2008 * Construct a JSON-serializable object representing the content of the store.
2010 * @return {Object} Module store contents.
2012 toJSON: function () {
2013 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2017 * Get the localStorage key for the entire module store. The key references
2018 * $wgDBname to prevent clashes between wikis which share a common host.
2020 * @return {string} localStorage item key
2022 getStoreKey: function () {
2023 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2027 * Get a key on which to vary the module cache.
2029 * @return {string} String of concatenated vary conditions.
2031 getVary: function () {
2033 mw
.config
.get( 'skin' ),
2034 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2035 mw
.config
.get( 'wgUserLanguage' )
2040 * Initialize the store.
2042 * Retrieves store from localStorage and (if successfully retrieved) decoding
2043 * the stored JSON value to a plain object.
2045 * The try / catch block is used for JSON & localStorage feature detection.
2046 * See the in-line documentation for Modernizr's localStorage feature detection
2047 * code for a full account of why we need a try / catch:
2048 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2053 if ( mw
.loader
.store
.enabled
!== null ) {
2059 // Disabled because localStorage quotas are tight and (in Firefox's case)
2060 // shared by multiple origins.
2061 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2062 /Firefox|Opera/.test( navigator
.userAgent
) ||
2064 // Disabled by configuration.
2065 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2067 // Clear any previous store to free up space. (T66721)
2068 mw
.loader
.store
.clear();
2069 mw
.loader
.store
.enabled
= false;
2072 if ( mw
.config
.get( 'debug' ) ) {
2073 // Disable module store in debug mode
2074 mw
.loader
.store
.enabled
= false;
2079 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2080 // If we get here, localStorage is available; mark enabled
2081 mw
.loader
.store
.enabled
= true;
2082 data
= JSON
.parse( raw
);
2083 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2084 mw
.loader
.store
.items
= data
.items
;
2088 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2091 if ( raw
=== undefined ) {
2092 // localStorage failed; disable store
2093 mw
.loader
.store
.enabled
= false;
2095 mw
.loader
.store
.update();
2100 * Retrieve a module from the store and update cache hit stats.
2102 * @param {string} module Module name
2103 * @return {string|boolean} Module implementation or false if unavailable
2105 get: function ( module
) {
2108 if ( !mw
.loader
.store
.enabled
) {
2112 key
= getModuleKey( module
);
2113 if ( key
in mw
.loader
.store
.items
) {
2114 mw
.loader
.store
.stats
.hits
++;
2115 return mw
.loader
.store
.items
[ key
];
2117 mw
.loader
.store
.stats
.misses
++;
2122 * Stringify a module and queue it for storage.
2124 * @param {string} module Module name
2125 * @param {Object} descriptor The module's descriptor as set in the registry
2126 * @return {boolean} Module was set
2128 set: function ( module
, descriptor
) {
2131 if ( !mw
.loader
.store
.enabled
) {
2135 key
= getModuleKey( module
);
2138 // Already stored a copy of this exact version
2139 key
in mw
.loader
.store
.items
||
2140 // Module failed to load
2141 descriptor
.state
!== 'ready' ||
2142 // Unversioned, private, or site-/user-specific
2143 !descriptor
.version
||
2144 descriptor
.group
=== 'private' ||
2145 descriptor
.group
=== 'user' ||
2146 // Partial descriptor
2147 // (e.g. skipped module, or style module with state=ready)
2148 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2149 descriptor
.templates
].indexOf( undefined ) !== -1
2157 JSON
.stringify( key
),
2158 typeof descriptor
.script
=== 'function' ?
2159 String( descriptor
.script
) :
2160 JSON
.stringify( descriptor
.script
),
2161 JSON
.stringify( descriptor
.style
),
2162 JSON
.stringify( descriptor
.messages
),
2163 JSON
.stringify( descriptor
.templates
)
2165 // Attempted workaround for a possible Opera bug (bug T59567).
2166 // This regex should never match under sane conditions.
2167 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2168 args
[ 1 ] = 'function' + args
[ 1 ];
2169 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2172 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2176 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2177 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2180 mw
.loader
.store
.items
[ key
] = src
;
2181 mw
.loader
.store
.update();
2186 * Iterate through the module store, removing any item that does not correspond
2187 * (in name and version) to an item in the module registry.
2189 * @return {boolean} Store was pruned
2191 prune: function () {
2194 if ( !mw
.loader
.store
.enabled
) {
2198 for ( key
in mw
.loader
.store
.items
) {
2199 module
= key
.slice( 0, key
.indexOf( '@' ) );
2200 if ( getModuleKey( module
) !== key
) {
2201 mw
.loader
.store
.stats
.expired
++;
2202 delete mw
.loader
.store
.items
[ key
];
2203 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2204 // This value predates the enforcement of a size limit on cached modules.
2205 delete mw
.loader
.store
.items
[ key
];
2212 * Clear the entire module store right now.
2214 clear: function () {
2215 mw
.loader
.store
.items
= {};
2217 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2218 } catch ( ignored
) {}
2222 * Sync in-memory store back to localStorage.
2224 * This function debounces updates. When called with a flush already pending,
2225 * the call is coalesced into the pending update. The call to
2226 * localStorage.setItem will be naturally deferred until the page is quiescent.
2228 * Because localStorage is shared by all pages from the same origin, if multiple
2229 * pages are loaded with different module sets, the possibility exists that
2230 * modules saved by one page will be clobbered by another. But the impact would
2231 * be minor and the problem would be corrected by subsequent page views.
2235 update
: ( function () {
2236 var hasPendingWrite
= false;
2238 function flushWrites() {
2240 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2244 mw
.loader
.store
.prune();
2245 key
= mw
.loader
.store
.getStoreKey();
2247 // Replacing the content of the module store might fail if the new
2248 // contents would exceed the browser's localStorage size limit. To
2249 // avoid clogging the browser with stale data, always remove the old
2250 // value before attempting to set the new one.
2251 localStorage
.removeItem( key
);
2252 data
= JSON
.stringify( mw
.loader
.store
);
2253 localStorage
.setItem( key
, data
);
2255 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2258 hasPendingWrite
= false;
2261 return function () {
2262 if ( !hasPendingWrite
) {
2263 hasPendingWrite
= true;
2264 mw
.requestIdleCallback( flushWrites
);
2273 * HTML construction helper functions
2280 * output = Html.element( 'div', {}, new Html.Raw(
2281 * Html.element( 'img', { src: '<' } )
2283 * mw.log( output ); // <div><img src="<"/></div>
2288 html
: ( function () {
2289 function escapeCallback( s
) {
2306 * Escape a string for HTML.
2308 * Converts special characters to HTML entities.
2310 * mw.html.escape( '< > \' & "' );
2311 * // Returns < > ' & "
2313 * @param {string} s The string to escape
2314 * @return {string} HTML
2316 escape: function ( s
) {
2317 return s
.replace( /['"<>&]/g, escapeCallback
);
2321 * Create an HTML element string, with safe escaping.
2323 * @param {string} name The tag name.
2324 * @param {Object} [attrs] An object with members mapping element names to values
2325 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2327 * - string: Text to be escaped.
2328 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2329 * - this.Raw: The raw value is directly included.
2330 * - this.Cdata: The raw value is directly included. An exception is
2331 * thrown if it contains any illegal ETAGO delimiter.
2332 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2333 * @return {string} HTML
2335 element: function ( name
, attrs
, contents
) {
2336 var v
, attrName
, s
= '<' + name
;
2339 for ( attrName
in attrs
) {
2340 v
= attrs
[ attrName
];
2341 // Convert name=true, to name=name
2345 } else if ( v
=== false ) {
2348 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2351 if ( contents
=== undefined || contents
=== null ) {
2358 switch ( typeof contents
) {
2361 s
+= this.escape( contents
);
2365 // Convert to string
2366 s
+= String( contents
);
2369 if ( contents
instanceof this.Raw
) {
2370 // Raw HTML inclusion
2371 s
+= contents
.value
;
2372 } else if ( contents
instanceof this.Cdata
) {
2374 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2375 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2377 s
+= contents
.value
;
2379 throw new Error( 'mw.html.element: Invalid type of contents' );
2382 s
+= '</' + name
+ '>';
2387 * Wrapper object for raw HTML passed to mw.html.element().
2389 * @class mw.html.Raw
2391 * @param {string} value
2393 Raw: function ( value
) {
2398 * Wrapper object for CDATA element contents passed to mw.html.element()
2400 * @class mw.html.Cdata
2402 * @param {string} value
2404 Cdata: function ( value
) {
2410 // Skeleton user object, extended by the 'mediawiki.user' module.
2417 * @property {mw.Map}
2421 * @property {mw.Map}
2426 // OOUI widgets specific to MediaWiki
2430 * Registry and firing of events.
2432 * MediaWiki has various interface components that are extended, enhanced
2433 * or manipulated in some other way by extensions, gadgets and even
2436 * This framework helps streamlining the timing of when these other
2437 * code paths fire their plugins (instead of using document-ready,
2438 * which can and should be limited to firing only once).
2440 * Features like navigating to other wiki pages, previewing an edit
2441 * and editing itself – without a refresh – can then retrigger these
2442 * hooks accordingly to ensure everything still works as expected.
2446 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2447 * mw.hook( 'wikipage.content' ).fire( $content );
2449 * Handlers can be added and fired for arbitrary event names at any time. The same
2450 * event can be fired multiple times. The last run of an event is memorized
2451 * (similar to `$(document).ready` and `$.Deferred().done`).
2452 * This means if an event is fired, and a handler added afterwards, the added
2453 * function will be fired right away with the last given event data.
2455 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2456 * Thus allowing flexible use and optimal maintainability and authority control.
2457 * You can pass around the `add` and/or `fire` method to another piece of code
2458 * without it having to know the event name (or `mw.hook` for that matter).
2460 * var h = mw.hook( 'bar.ready' );
2461 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2463 * Note: Events are documented with an underscore instead of a dot in the event
2464 * name due to jsduck not supporting dots in that position.
2468 hook
: ( function () {
2472 * Create an instance of mw.hook.
2476 * @param {string} name Name of hook.
2479 return function ( name
) {
2480 var list
= hasOwn
.call( lists
, name
) ?
2482 lists
[ name
] = $.Callbacks( 'memory' );
2486 * Register a hook handler
2488 * @param {...Function} handler Function to bind.
2494 * Unregister a hook handler
2496 * @param {...Function} handler Function to unbind.
2499 remove
: list
.remove
,
2504 * @param {...Mixed} data
2509 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2516 // Alias $j to jQuery for backwards compatibility
2517 // @deprecated since 1.23 Use $ or jQuery instead
2518 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2521 * Log a message to window.console, if possible.
2523 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2524 * also in production mode). Gets console references in each invocation instead of caching the
2525 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2528 * @param {string} topic Stream name passed by mw.track
2529 * @param {Object} data Data passed by mw.track
2530 * @param {Error} [data.exception]
2531 * @param {string} data.source Error source
2532 * @param {string} [data.module] Name of module which caused the error
2534 function logError( topic
, data
) {
2535 /* eslint-disable no-console */
2538 source
= data
.source
,
2539 module
= data
.module
,
2540 console
= window
.console
;
2542 if ( console
&& console
.log
) {
2543 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2545 msg
+= ' in module ' + module
;
2547 msg
+= ( e
? ':' : '.' );
2550 // If we have an exception object, log it to the warning channel to trigger
2551 // proper stacktraces in browsers that support it.
2552 if ( e
&& console
.warn
) {
2556 /* eslint-enable no-console */
2559 // Subscribe to error streams
2560 mw
.trackSubscribe( 'resourceloader.exception', logError
);
2561 mw
.trackSubscribe( 'resourceloader.assert', logError
);
2563 // Attach to window and globally alias
2564 window
.mw
= window
.mediaWiki
= mw
;