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
,
19 * FNV132 hash function
21 * This function implements the 32-bit version of FNV-1.
22 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
23 * its output is base 36 rather than hex.
24 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
27 * @param {string} str String to hash
28 * @return {string} hash as an seven-character base 36 string
30 function fnv132( str
) {
31 /* eslint-disable no-bitwise */
32 var hash
= 0x811C9DC5,
35 for ( i
= 0; i
< str
.length
; i
++ ) {
36 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
37 hash
^= str
.charCodeAt( i
);
40 hash
= ( hash
>>> 0 ).toString( 36 );
41 while ( hash
.length
< 7 ) {
46 /* eslint-enable no-bitwise */
49 function defineFallbacks() {
50 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
51 StringSet
= window
.Set
|| ( function () {
56 function StringSet() {
59 StringSet
.prototype.add = function ( value
) {
60 this.set[ value
] = true;
62 StringSet
.prototype.has = function ( value
) {
63 return hasOwn
.call( this.set, value
);
70 * Alias property to the global object.
77 * @param {Mixed} value
79 function setGlobalMapValue( map
, key
, value
) {
80 map
.values
[ key
] = value
;
85 // Deprecation notice for mw.config globals (T58550, T72470)
86 map
=== mw
.config
&& 'Use mw.config instead.'
91 * Log a message to window.console, if possible.
93 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
94 * also in production mode). Gets console references in each invocation instead of caching the
95 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
98 * @param {string} topic Stream name passed by mw.track
99 * @param {Object} data Data passed by mw.track
100 * @param {Error} [data.exception]
101 * @param {string} data.source Error source
102 * @param {string} [data.module] Name of module which caused the error
104 function logError( topic
, data
) {
105 /* eslint-disable no-console */
108 source
= data
.source
,
109 module
= data
.module
,
110 console
= window
.console
;
112 if ( console
&& console
.log
) {
113 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
115 msg
+= ' in module ' + module
;
117 msg
+= ( e
? ':' : '.' );
120 // If we have an exception object, log it to the warning channel to trigger
121 // proper stacktraces in browsers that support it.
122 if ( e
&& console
.warn
) {
126 /* eslint-enable no-console */
130 * Create an object that can be read from or written to via methods that allow
131 * interaction both with single and multiple properties at once.
137 * @param {boolean} [global=false] Whether to synchronise =values to the global
138 * window object (for backwards-compatibility with mw.config; T72470). Values are
139 * copied in one direction only. Changes to globals do not reflect in the map.
141 function Map( global
) {
143 if ( global
=== true ) {
144 // Override #set to also set the global variable
145 this.set = function ( selection
, value
) {
147 if ( arguments
.length
> 1 ) {
148 if ( typeof selection
!== 'string' ) {
151 setGlobalMapValue( this, selection
, value
);
154 if ( typeof selection
=== 'object' ) {
155 for ( s
in selection
) {
156 setGlobalMapValue( this, s
, selection
[ s
] );
169 * Get the value of one or more keys.
171 * If called with no arguments, all values are returned.
173 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
174 * @param {Mixed} [fallback=null] Value for keys that don't exist.
175 * @return {Mixed|Object|null} If selection was a string, returns the value,
176 * If selection was an array, returns an object of key/values.
177 * If no selection is passed, a new object with all key/values is returned.
179 get: function ( selection
, fallback
) {
181 fallback
= arguments
.length
> 1 ? fallback
: null;
183 if ( Array
.isArray( selection
) ) {
185 for ( i
= 0; i
< selection
.length
; i
++ ) {
186 if ( typeof selection
[ i
] === 'string' ) {
187 results
[ selection
[ i
] ] = hasOwn
.call( this.values
, selection
[ i
] ) ?
188 this.values
[ selection
[ i
] ] :
195 if ( typeof selection
=== 'string' ) {
196 return hasOwn
.call( this.values
, selection
) ?
197 this.values
[ selection
] :
201 if ( selection
=== undefined ) {
203 for ( i
in this.values
) {
204 results
[ i
] = this.values
[ i
];
209 // Invalid selection key
214 * Set one or more key/value pairs.
216 * @param {string|Object} selection Key to set value for, or object mapping keys to values
217 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
218 * @return {boolean} True on success, false on failure
220 set: function ( selection
, value
) {
222 // Use `arguments.length` because `undefined` is also a valid value.
223 if ( arguments
.length
> 1 ) {
224 if ( typeof selection
!== 'string' ) {
227 this.values
[ selection
] = value
;
230 if ( typeof selection
=== 'object' ) {
231 for ( s
in selection
) {
232 this.values
[ s
] = selection
[ s
];
240 * Check if one or more keys exist.
242 * @param {Mixed} selection Key or array of keys to check
243 * @return {boolean} True if the key(s) exist
245 exists: function ( selection
) {
247 if ( Array
.isArray( selection
) ) {
248 for ( i
= 0; i
< selection
.length
; i
++ ) {
249 if ( typeof selection
[ i
] !== 'string' || !hasOwn
.call( this.values
, selection
[ i
] ) ) {
255 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
261 /* eslint-disable no-console */
262 log
= ( function () {
264 * Write a verbose message to the browser's console in debug mode.
266 * This method is mainly intended for verbose logging. It is a no-op in production mode.
267 * In ResourceLoader debug mode, it will use the browser's console if available, with
268 * fallback to creating a console interface in the DOM and logging messages there.
270 * See {@link mw.log} for other logging methods.
273 * @param {...string} msg Messages to output to console.
275 var log = function () {},
276 console
= window
.console
;
278 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
279 // when adding or removing mw.log methods below!
282 * Collection of methods to help log messages to the console.
289 * Write a message to the browser console's warning channel.
291 * This method is a no-op in browsers that don't implement the Console API.
293 * @param {...string} msg Messages to output to console
295 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
296 Function
.prototype.bind
.call( console
.warn
, console
) :
300 * Write a message to the browser console's error channel.
302 * Most browsers also print a stacktrace when calling this method if the
303 * argument is an Error object.
305 * This method is a no-op in browsers that don't implement the Console API.
308 * @param {...Mixed} msg Messages to output to console
310 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
311 Function
.prototype.bind
.call( console
.error
, console
) :
315 * Create a property on a host object that, when accessed, will produce
316 * a deprecation warning in the console.
318 * @param {Object} obj Host object of deprecated property
319 * @param {string} key Name of property to create in `obj`
320 * @param {Mixed} val The value this property should return when accessed
321 * @param {string} [msg] Optional text to include in the deprecation message
322 * @param {string} [logName=key] Optional custom name for the feature.
323 * This is used instead of `key` in the message and `mw.deprecate` tracking.
325 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
327 } : function ( obj
, key
, val
, msg
, logName
) {
328 var logged
= new StringSet();
329 logName
= logName
|| key
;
330 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
331 function uniqueTrace() {
332 var trace
= new Error().stack
;
333 if ( logged
.has( trace
) ) {
339 // Support: Safari 5.0
340 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
341 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
343 Object
.defineProperty( obj
, key
, {
347 if ( uniqueTrace() ) {
348 mw
.track( 'mw.deprecate', logName
);
353 set: function ( newVal
) {
354 if ( uniqueTrace() ) {
355 mw
.track( 'mw.deprecate', logName
);
368 /* eslint-enable no-console */
374 redefineFallbacksForTest: function () {
375 if ( !window
.QUnit
) {
376 throw new Error( 'Reset not allowed outside unit tests' );
382 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
384 * On browsers that implement the Navigation Timing API, this function will produce floating-point
385 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
386 * it will fall back to using `Date`.
388 * @return {number} Current time
391 var perf
= window
.performance
,
392 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
393 return navStart
&& typeof perf
.now
=== 'function' ?
394 function () { return navStart
+ perf
.now(); } :
395 function () { return Date
.now(); };
399 * List of all analytic events emitted so far.
404 trackQueue
: trackQueue
,
406 track: function ( topic
, data
) {
407 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
408 // The base module extends this method to fire events here
412 * Track an early error event via mw.track and send it to the window console.
415 * @param {string} topic Topic name
416 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
418 trackError: function ( topic
, data
) {
419 mw
.track( topic
, data
);
420 logError( topic
, data
);
423 // Expose Map constructor
427 * Map of configuration values.
429 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
432 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
433 * global `window` object.
435 * @property {mw.Map} config
437 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
441 * Empty object for third-party libraries, for cases where you don't
442 * want to add a new global, or the global is bad and needs containment
450 * Access container for deprecated functionality that can be moved from
451 * from their legacy location and attached to this object (e.g. a global
452 * function that is deprecated and as stop-gap can be exposed through here).
454 * This was reserved for future use but never ended up being used.
456 * @deprecated since 1.22 Let deprecated identifiers keep their original name
457 * and use mw.log#deprecate to create an access container for tracking.
463 * Store for messages.
470 * Store for templates associated with a module.
474 templates
: new Map(),
480 * Client for ResourceLoader server end point.
482 * This client is in charge of maintaining the module registry and state
483 * machine, initiating network (batch) requests for loading modules, as
484 * well as dependency resolution and execution of source code.
486 * For more information, refer to
487 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
492 loader
: ( function () {
495 * Fired via mw.track on various resource loading errors.
497 * @event resourceloader_exception
498 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
499 * object, but in theory module code could manually throw something else, and that
500 * might also end up here.
501 * @param {string} [module] Name of the module which caused the error. Omitted if the
502 * error is not module-related or the module cannot be easily identified due to
504 * @param {string} source Source of the error. Possible values:
506 * - style: stylesheet error (only affects old IE where a special style loading method
508 * - load-callback: exception thrown by user callback
509 * - module-execute: exception thrown by module code
510 * - resolve: failed to sort dependencies for a module in mw.loader.load
511 * - store-eval: could not evaluate module code cached in localStorage
512 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
513 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
514 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
518 * Fired via mw.track on resource loading error conditions.
520 * @event resourceloader_assert
521 * @param {string} source Source of the error. Possible values:
523 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
524 * bug; see <https://phabricator.wikimedia.org/T59567> for details
528 * Mapping of registered modules.
530 * See #implement and #execute for exact details on support for script, style and messages.
536 * // From mw.loader.register()
537 * 'version': '########' (hash)
538 * 'dependencies': ['required.foo', 'bar.also', ...]
539 * 'group': 'somegroup', (or) null
540 * 'source': 'local', (or) 'anotherwiki'
541 * 'skip': 'return !!window.Example', (or) null
542 * 'module': export Object
544 * // Set from execute() or mw.loader.state()
545 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
547 * // Optionally added at run-time by mw.loader.implement()
549 * 'script': closure, array of urls, or string
550 * 'style': { ... } (see #execute)
551 * 'messages': { 'key': 'value', ... }
558 * The module is known to the system but not yet required.
559 * Meta data is registered via mw.loader#register. Calls to that method are
560 * generated server-side by the startup module.
562 * The module was required through mw.loader (either directly or as dependency of
563 * another module). The client will fetch module contents from the server.
564 * The contents are then stashed in the registry via mw.loader#implement.
566 * The module has been loaded from the server and stashed via mw.loader#implement.
567 * If the module has no more dependencies in-flight, the module will be executed
568 * immediately. Otherwise execution is deferred, controlled via #handlePending.
570 * The module is being executed.
572 * The module has been successfully executed.
574 * The module (or one of its dependencies) produced an error during execution.
576 * The module was registered client-side and requested, but the server denied knowledge
577 * of the module's existence.
583 // Mapping of sources, keyed by source-id, values are strings.
588 // 'sourceId': 'http://example.org/w/load.php'
593 // For queueModuleScript()
594 handlingPendingRequests
= false,
595 pendingRequests
= [],
597 // List of modules to be loaded
601 * List of callback jobs waiting for modules to be ready.
603 * Jobs are created by #enqueue() and run by #handlePending().
605 * Typically when a job is created for a module, the job's dependencies contain
606 * both the required module and all its recursive dependencies.
611 * 'dependencies': [ module names ],
612 * 'ready': Function callback
613 * 'error': Function callback
616 * @property {Object[]} jobs
622 * For #addEmbeddedCSS() and #addLink()
625 * @property {HTMLElement|null} marker
627 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
629 // For addEmbeddedCSS()
631 cssBufferTimer
= null,
633 rAF
= window
.requestAnimationFrame
|| setTimeout
;
636 * Create a new style element and add it to the DOM.
639 * @param {string} text CSS text
640 * @param {Node|null} [nextNode] The element where the style tag
641 * should be inserted before
642 * @return {HTMLElement} Reference to the created style element
644 function newStyleTag( text
, nextNode
) {
645 var el
= document
.createElement( 'style' );
646 el
.appendChild( document
.createTextNode( text
) );
647 if ( nextNode
&& nextNode
.parentNode
) {
648 nextNode
.parentNode
.insertBefore( el
, nextNode
);
650 document
.head
.appendChild( el
);
656 * Add a bit of CSS text to the current browser page.
658 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
659 * or create a new one based on whether the given `cssText` is safe for extension.
662 * @param {string} [cssText=cssBuffer] If called without cssText,
663 * the internal buffer will be inserted instead.
664 * @param {Function} [callback]
666 function addEmbeddedCSS( cssText
, callback
) {
667 function fireCallbacks() {
669 oldCallbacks
= cssCallbacks
;
670 // Reset cssCallbacks variable so it's not polluted by any calls to
671 // addEmbeddedCSS() from one of the callbacks (T105973)
673 for ( i
= 0; i
< oldCallbacks
.length
; i
++ ) {
679 cssCallbacks
.push( callback
);
682 // Yield once before creating the <style> tag. This lets multiple stylesheets
683 // accumulate into one buffer, allowing us to reduce how often new stylesheets
684 // are inserted in the browser. Appending a stylesheet and waiting for the
685 // browser to repaint is fairly expensive. (T47810)
687 // Don't extend the buffer if the item needs its own stylesheet.
688 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
689 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
690 // Linebreak for somewhat distinguishable sections
691 cssBuffer
+= '\n' + cssText
;
692 if ( !cssBufferTimer
) {
693 cssBufferTimer
= rAF( function () {
694 // Wrap in anonymous function that takes no arguments
695 // Support: Firefox < 13
696 // Firefox 12 has non-standard behaviour of passing a number
697 // as first argument to a setTimeout callback.
698 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
705 // This is a scheduled flush for the buffer
707 cssBufferTimer
= null;
712 newStyleTag( cssText
, marker
);
719 * @param {Array} modules List of module names
720 * @return {string} Hash of concatenated version hashes.
722 function getCombinedVersion( modules
) {
723 var hashes
= modules
.map( function ( module
) {
724 return registry
[ module
].version
;
726 return fnv132( hashes
.join( '' ) );
730 * Determine whether all dependencies are in state 'ready', which means we may
731 * execute the module or job now.
734 * @param {Array} modules Names of modules to be checked
735 * @return {boolean} True if all modules are in state 'ready', false otherwise
737 function allReady( modules
) {
739 for ( i
= 0; i
< modules
.length
; i
++ ) {
740 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
748 * Determine whether all dependencies are in state 'ready', which means we may
749 * execute the module or job now.
752 * @param {Array} modules Names of modules to be checked
753 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
755 function anyFailed( modules
) {
757 for ( i
= 0; i
< modules
.length
; i
++ ) {
758 state
= mw
.loader
.getState( modules
[ i
] );
759 if ( state
=== 'error' || state
=== 'missing' ) {
767 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
768 * pending jobs and modules that depend upon this module. If the given module failed,
769 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
770 * all jobs/modules now having their dependencies satisfied.
772 * Jobs that depend on a failed module, will have their error callback ran (if any).
775 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
777 function handlePending( module
) {
778 var j
, job
, hasErrors
, m
, stateChange
;
780 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
781 // If the current module failed, mark all dependent modules also as failed.
782 // Iterate until steady-state to propagate the error state upwards in the
786 for ( m
in registry
) {
787 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
788 if ( anyFailed( registry
[ m
].dependencies
) ) {
789 registry
[ m
].state
= 'error';
794 } while ( stateChange
);
797 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
798 for ( j
= 0; j
< jobs
.length
; j
++ ) {
799 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
800 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
801 // All dependencies satisfied, or some have errors
807 if ( typeof job
.error
=== 'function' ) {
808 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
811 if ( typeof job
.ready
=== 'function' ) {
816 // A user-defined callback raised an exception.
817 // Swallow it to protect our state machine!
818 mw
.trackError( 'resourceloader.exception', {
821 source
: 'load-callback'
827 if ( registry
[ module
].state
=== 'ready' ) {
828 // The current module became 'ready'. Set it in the module store, and recursively execute all
829 // dependent modules that are loaded and now have all dependencies satisfied.
830 mw
.loader
.store
.set( module
, registry
[ module
] );
831 for ( m
in registry
) {
832 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
833 // eslint-disable-next-line no-use-before-define
841 * Resolve dependencies and detect circular references.
844 * @param {string} module Name of the top-level module whose dependencies shall be
845 * resolved and sorted.
846 * @param {Array} resolved Returns a topological sort of the given module and its
847 * dependencies, such that later modules depend on earlier modules. The array
848 * contains the module names. If the array contains already some module names,
849 * this function appends its result to the pre-existing array.
850 * @param {StringSet} [unresolved] Used to track the current dependency
851 * chain, and to report loops in the dependency graph.
852 * @throws {Error} If any unregistered module or a dependency loop is encountered
854 function sortDependencies( module
, resolved
, unresolved
) {
857 if ( !hasOwn
.call( registry
, module
) ) {
858 throw new Error( 'Unknown dependency: ' + module
);
861 if ( registry
[ module
].skip
!== null ) {
862 // eslint-disable-next-line no-new-func
863 skip
= new Function( registry
[ module
].skip
);
864 registry
[ module
].skip
= null;
866 registry
[ module
].skipped
= true;
867 registry
[ module
].dependencies
= [];
868 registry
[ module
].state
= 'ready';
869 handlePending( module
);
874 if ( resolved
.indexOf( module
) !== -1 ) {
875 // Module already resolved; nothing to do
878 // Create unresolved if not passed in
880 unresolved
= new StringSet();
882 // Tracks down dependencies
883 deps
= registry
[ module
].dependencies
;
884 for ( i
= 0; i
< deps
.length
; i
++ ) {
885 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
886 if ( unresolved
.has( deps
[ i
] ) ) {
888 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
892 unresolved
.add( module
);
893 sortDependencies( deps
[ i
], resolved
, unresolved
);
896 resolved
.push( module
);
900 * Get names of module that a module depends on, in their proper dependency order.
903 * @param {string[]} modules Array of string module names
904 * @return {Array} List of dependencies, including 'module'.
905 * @throws {Error} If an unregistered module or a dependency loop is encountered
907 function resolve( modules
) {
908 var i
, resolved
= [];
909 for ( i
= 0; i
< modules
.length
; i
++ ) {
910 sortDependencies( modules
[ i
], resolved
);
916 * Like #resolve(), except it will silently ignore modules that
917 * are missing or have missing dependencies.
920 * @param {string[]} modules Array of string module names
921 * @return {Array} List of dependencies.
923 function resolveStubbornly( modules
) {
924 var i
, saved
, resolved
= [];
925 for ( i
= 0; i
< modules
.length
; i
++ ) {
926 saved
= resolved
.slice();
928 sortDependencies( modules
[ i
], resolved
);
930 // This module is unknown or has unknown dependencies.
931 // Undo any incomplete resolutions made and keep going.
933 mw
.trackError( 'resourceloader.exception', {
943 * Load and execute a script.
946 * @param {string} src URL to script, will be used as the src attribute in the script tag
947 * @param {Function} [callback] Callback to run after request resolution
949 function addScript( src
, callback
) {
950 var script
= document
.createElement( 'script' );
952 script
.onload
= script
.onerror = function () {
953 if ( script
.parentNode
) {
954 script
.parentNode
.removeChild( script
);
962 document
.head
.appendChild( script
);
966 * Queue the loading and execution of a script for a particular module.
969 * @param {string} src URL of the script
970 * @param {string} moduleName Name of currently executing module
971 * @param {Function} callback Callback to run after addScript() resolution
973 function queueModuleScript( src
, moduleName
, callback
) {
974 pendingRequests
.push( function () {
975 if ( hasOwn
.call( registry
, moduleName
) ) {
976 // Emulate runScript() part of execute()
977 window
.require
= mw
.loader
.require
;
978 window
.module
= registry
[ moduleName
].module
;
980 addScript( src
, function () {
981 // 'module.exports' should not persist after the file is executed to
982 // avoid leakage to unrelated code. 'require' should be kept, however,
983 // as asynchronous access to 'require' is allowed and expected. (T144879)
984 delete window
.module
;
986 // Start the next one (if any)
987 if ( pendingRequests
[ 0 ] ) {
988 pendingRequests
.shift()();
990 handlingPendingRequests
= false;
994 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
995 handlingPendingRequests
= true;
996 pendingRequests
.shift()();
1001 * Utility function for execute()
1004 * @param {string} [media] Media attribute
1005 * @param {string} url URL
1007 function addLink( media
, url
) {
1008 var el
= document
.createElement( 'link' );
1010 el
.rel
= 'stylesheet';
1011 if ( media
&& media
!== 'all' ) {
1014 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1015 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1018 if ( marker
&& marker
.parentNode
) {
1019 marker
.parentNode
.insertBefore( el
, marker
);
1021 document
.head
.appendChild( el
);
1027 * @param {string} code JavaScript code
1029 function domEval( code
) {
1030 var script
= document
.createElement( 'script' );
1032 document
.head
.appendChild( script
);
1033 script
.parentNode
.removeChild( script
);
1037 * Add one or more modules to the module load queue.
1042 * @param {string|string[]} dependencies Module name or array of string module names
1043 * @param {Function} [ready] Callback to execute when all dependencies are ready
1044 * @param {Function} [error] Callback to execute when any dependency fails
1046 function enqueue( dependencies
, ready
, error
) {
1047 // Allow calling by single module name
1048 if ( typeof dependencies
=== 'string' ) {
1049 dependencies
= [ dependencies
];
1052 if ( allReady( dependencies
) ) {
1053 // Run ready immediately
1054 if ( ready
!== undefined ) {
1061 if ( anyFailed( dependencies
) ) {
1062 if ( error
!== undefined ) {
1063 // Execute error immediately if any dependencies have errors
1065 new Error( 'One or more dependencies failed to load' ),
1073 // Not all dependencies are ready, add to the load queue...
1075 // Add ready and error callbacks if they were given
1076 if ( ready
!== undefined || error
!== undefined ) {
1078 // Narrow down the list to modules that are worth waiting for
1079 dependencies
: dependencies
.filter( function ( module
) {
1080 var state
= mw
.loader
.getState( module
);
1081 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1088 dependencies
.forEach( function ( module
) {
1089 var state
= mw
.loader
.getState( module
);
1090 // Only queue modules that are still in the initial 'registered' state
1091 // (not ones already loading, ready or error).
1092 if ( state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1093 // Private modules must be embedded in the page. Don't bother queuing
1094 // these as the server will deny them anyway (T101806).
1095 if ( registry
[ module
].group
=== 'private' ) {
1096 registry
[ module
].state
= 'error';
1097 handlePending( module
);
1100 queue
.push( module
);
1108 * Executes a loaded module, making it ready to use
1111 * @param {string} module Module name to execute
1113 function execute( module
) {
1114 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1115 cssHandlesRegistered
= false;
1117 if ( !hasOwn
.call( registry
, module
) ) {
1118 throw new Error( 'Module has not been registered yet: ' + module
);
1120 if ( registry
[ module
].state
!== 'loaded' ) {
1121 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1124 registry
[ module
].state
= 'executing';
1126 runScript = function () {
1127 var script
, markModuleReady
, nestedAddScript
;
1129 script
= registry
[ module
].script
;
1130 markModuleReady = function () {
1131 registry
[ module
].state
= 'ready';
1132 handlePending( module
);
1134 nestedAddScript = function ( arr
, callback
, i
) {
1135 // Recursively call queueModuleScript() in its own callback
1136 // for each element of arr.
1137 if ( i
>= arr
.length
) {
1138 // We're at the end of the array
1143 queueModuleScript( arr
[ i
], module
, function () {
1144 nestedAddScript( arr
, callback
, i
+ 1 );
1149 if ( Array
.isArray( script
) ) {
1150 nestedAddScript( script
, markModuleReady
, 0 );
1151 } else if ( typeof script
=== 'function' ) {
1152 // Pass jQuery twice so that the signature of the closure which wraps
1153 // the script can bind both '$' and 'jQuery'.
1154 script( window
.$, window
.$, mw
.loader
.require
, registry
[ module
].module
);
1157 } else if ( typeof script
=== 'string' ) {
1158 // Site and user modules are legacy scripts that run in the global scope.
1159 // This is transported as a string instead of a function to avoid needing
1160 // to use string manipulation to undo the function wrapper.
1165 // Module without script
1169 // Use mw.track instead of mw.log because these errors are common in production mode
1170 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1171 registry
[ module
].state
= 'error';
1172 mw
.trackError( 'resourceloader.exception', {
1173 exception
: e
, module
:
1174 module
, source
: 'module-execute'
1176 handlePending( module
);
1180 // Add localizations to message system
1181 if ( registry
[ module
].messages
) {
1182 mw
.messages
.set( registry
[ module
].messages
);
1185 // Initialise templates
1186 if ( registry
[ module
].templates
) {
1187 mw
.templates
.set( module
, registry
[ module
].templates
);
1190 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1193 checkCssHandles = function () {
1194 var ex
, dependencies
;
1195 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1196 // one of the cssHandles is fired while we're still creating more handles.
1197 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1198 if ( module
=== 'user' ) {
1199 // Implicit dependency on the site module. Not real dependency because
1200 // it should run after 'site' regardless of whether it succeeds or fails.
1201 // Note: This is a simplified version of mw.loader.using(), inlined here
1202 // as using() depends on jQuery (T192623).
1204 dependencies
= resolve( [ 'site' ] );
1209 if ( ex
=== undefined ) {
1210 enqueue( dependencies
, runScript
, runScript
);
1215 runScript
= undefined; // Revoke
1218 cssHandle = function () {
1219 var check
= checkCssHandles
;
1221 return function () {
1225 check
= undefined; // Revoke
1231 // Process styles (see also mw.loader.implement)
1232 // * back-compat: { <media>: css }
1233 // * back-compat: { <media>: [url, ..] }
1234 // * { "css": [css, ..] }
1235 // * { "url": { <media>: [url, ..] } }
1236 if ( registry
[ module
].style
) {
1237 for ( key
in registry
[ module
].style
) {
1238 value
= registry
[ module
].style
[ key
];
1241 if ( key
!== 'url' && key
!== 'css' ) {
1242 // Backwards compatibility, key is a media-type
1243 if ( typeof value
=== 'string' ) {
1244 // back-compat: { <media>: css }
1245 // Ignore 'media' because it isn't supported (nor was it used).
1246 // Strings are pre-wrapped in "@media". The media-type was just ""
1247 // (because it had to be set to something).
1248 // This is one of the reasons why this format is no longer used.
1249 addEmbeddedCSS( value
, cssHandle() );
1251 // back-compat: { <media>: [url, ..] }
1257 // Array of css strings in key 'css',
1258 // or back-compat array of urls from media-type
1259 if ( Array
.isArray( value
) ) {
1260 for ( i
= 0; i
< value
.length
; i
++ ) {
1261 if ( key
=== 'bc-url' ) {
1262 // back-compat: { <media>: [url, ..] }
1263 addLink( media
, value
[ i
] );
1264 } else if ( key
=== 'css' ) {
1265 // { "css": [css, ..] }
1266 addEmbeddedCSS( value
[ i
], cssHandle() );
1269 // Not an array, but a regular object
1270 // Array of urls inside media-type key
1271 } else if ( typeof value
=== 'object' ) {
1272 // { "url": { <media>: [url, ..] } }
1273 for ( media
in value
) {
1274 urls
= value
[ media
];
1275 for ( i
= 0; i
< urls
.length
; i
++ ) {
1276 addLink( media
, urls
[ i
] );
1284 cssHandlesRegistered
= true;
1288 function sortQuery( o
) {
1297 for ( key
= 0; key
< a
.length
; key
++ ) {
1298 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1304 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1305 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1307 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1308 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1310 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1311 * because its implementation needs to keep track of potential string size in order
1312 * to decide when to split the requests due to url size.
1315 * @param {Object} moduleMap Module map
1317 * @return {string} return.str Module query string
1318 * @return {Array} return.list List of module names in matching order
1320 function buildModulesString( moduleMap
) {
1325 function restore( suffix
) {
1329 for ( prefix
in moduleMap
) {
1330 p
= prefix
=== '' ? '' : prefix
+ '.';
1331 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1332 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1335 str
: str
.join( '|' ),
1341 * Resolve indexed dependencies.
1343 * ResourceLoader uses an optimization to save space which replaces module names in
1344 * dependency lists with the index of that module within the array of module
1345 * registration data if it exists. The benefit is a significant reduction in the data
1346 * size of the startup module. This function changes those dependency lists back to
1347 * arrays of strings.
1350 * @param {Array} modules Modules array
1352 function resolveIndexedDependencies( modules
) {
1354 function resolveIndex( dep
) {
1355 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1357 for ( i
= 0; i
< modules
.length
; i
++ ) {
1358 deps
= modules
[ i
][ 2 ];
1360 for ( j
= 0; j
< deps
.length
; j
++ ) {
1361 deps
[ j
] = resolveIndex( deps
[ j
] );
1369 * @param {Object} params Map of parameter names to values
1372 function makeQueryString( params
) {
1373 return Object
.keys( params
).map( function ( key
) {
1374 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1379 * Create network requests for a batch of modules.
1381 * This is an internal method for #work(). This must not be called directly
1382 * unless the modules are already registered, and no request is in progress,
1383 * and the module state has already been set to `loading`.
1386 * @param {string[]} batch
1388 function batchRequest( batch
) {
1389 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1390 source
, group
, i
, modules
, sourceLoadScript
,
1391 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1392 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1395 * Start the currently drafted request to the server.
1399 function doRequest() {
1400 // Optimisation: Inherit (Object.create), not copy ($.extend)
1401 var query
= Object
.create( currReqBase
),
1402 packed
= buildModulesString( moduleMap
);
1403 query
.modules
= packed
.str
;
1404 // The packing logic can change the effective order, even if the input was
1405 // sorted. As such, the call to getCombinedVersion() must use this
1406 // effective order, instead of currReqModules, as otherwise the combined
1407 // version will not match the hash expected by the server based on
1408 // combining versions from the module query string in-order. (T188076)
1409 query
.version
= getCombinedVersion( packed
.list
);
1410 query
= sortQuery( query
);
1411 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1414 if ( !batch
.length
) {
1418 // Always order modules alphabetically to help reduce cache
1419 // misses for otherwise identical content.
1422 // Query parameters common to all requests
1424 skin
: mw
.config
.get( 'skin' ),
1425 lang
: mw
.config
.get( 'wgUserLanguage' ),
1426 debug
: mw
.config
.get( 'debug' )
1428 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1430 // Split module list by source and by group.
1432 for ( b
= 0; b
< batch
.length
; b
++ ) {
1433 bSource
= registry
[ batch
[ b
] ].source
;
1434 bGroup
= registry
[ batch
[ b
] ].group
;
1435 if ( !hasOwn
.call( splits
, bSource
) ) {
1436 splits
[ bSource
] = {};
1438 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1439 splits
[ bSource
][ bGroup
] = [];
1441 bSourceGroup
= splits
[ bSource
][ bGroup
];
1442 bSourceGroup
.push( batch
[ b
] );
1445 for ( source
in splits
) {
1447 sourceLoadScript
= sources
[ source
];
1449 for ( group
in splits
[ source
] ) {
1451 // Cache access to currently selected list of
1452 // modules for this group from this source.
1453 modules
= splits
[ source
][ group
];
1455 // Query parameters common to requests for this module group
1456 // Optimisation: Inherit (Object.create), not copy ($.extend)
1457 currReqBase
= Object
.create( reqBase
);
1458 // User modules require a user name in the query string.
1459 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1460 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1463 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1464 // > '&modules='.length === 9
1465 // > '&version=1234567'.length === 16
1467 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1469 // We may need to split up the request to honor the query string length limit,
1470 // so build it piece by piece.
1471 l
= currReqBaseLength
;
1472 moduleMap
= {}; // { prefix: [ suffixes ] }
1473 currReqModules
= [];
1475 for ( i
= 0; i
< modules
.length
; i
++ ) {
1476 // Determine how many bytes this module would add to the query string
1477 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1478 // If lastDotIndex is -1, substr() returns an empty string
1479 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1480 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1481 bytesAdded
= hasOwn
.call( moduleMap
, prefix
) ?
1482 suffix
.length
+ 3 : // '%2C'.length == 3
1483 modules
[ i
].length
+ 3; // '%7C'.length == 3
1485 // If the url would become too long, create a new one, but don't create empty requests
1486 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1487 // Dispatch what we've got...
1489 // .. and start again.
1490 l
= currReqBaseLength
;
1492 currReqModules
= [];
1494 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1496 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1497 moduleMap
[ prefix
] = [];
1500 moduleMap
[ prefix
].push( suffix
);
1501 currReqModules
.push( modules
[ i
] );
1503 // If there's anything left in moduleMap, request that too
1504 if ( currReqModules
.length
) {
1513 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1514 * form of calls to mw.loader#implement().
1515 * @param {Function} cb Callback in case of failure
1516 * @param {Error} cb.err
1518 function asyncEval( implementations
, cb
) {
1519 if ( !implementations
.length
) {
1522 mw
.requestIdleCallback( function () {
1524 domEval( implementations
.join( ';' ) );
1532 * Make a versioned key for a specific module.
1535 * @param {string} module Module name
1536 * @return {string|null} Module key in format '`[name]@[version]`',
1537 * or null if the module does not exist
1539 function getModuleKey( module
) {
1540 return hasOwn
.call( registry
, module
) ?
1541 ( module
+ '@' + registry
[ module
].version
) : null;
1546 * @param {string} key Module name or '`[name]@[version]`'
1549 function splitModuleKey( key
) {
1550 var index
= key
.indexOf( '@' );
1551 if ( index
=== -1 ) {
1558 name
: key
.slice( 0, index
),
1559 version
: key
.slice( index
+ 1 )
1563 /* Public Members */
1566 * The module registry is exposed as an aid for debugging and inspecting page
1567 * state; it is not a public interface for modifying the registry.
1573 moduleRegistry
: registry
,
1576 * @inheritdoc #newStyleTag
1579 addStyleTag
: newStyleTag
,
1586 * Start loading of all queued module dependencies.
1591 var q
, batch
, implementations
, sourceModules
;
1595 // Appends a list of modules from the queue to the batch
1596 for ( q
= 0; q
< queue
.length
; q
++ ) {
1597 // Only load modules which are registered
1598 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1599 // Prevent duplicate entries
1600 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1601 batch
.push( queue
[ q
] );
1602 // Mark registered modules as loading
1603 registry
[ queue
[ q
] ].state
= 'loading';
1608 // Now that the queue has been processed into a batch, clear the queue.
1609 // This MUST happen before we initiate any eval or network request. Otherwise,
1610 // it is possible for a cached script to instantly trigger the same work queue
1611 // again; all before we've cleared it causing each request to include modules
1612 // which are already loaded.
1615 if ( !batch
.length
) {
1619 mw
.loader
.store
.init();
1620 if ( mw
.loader
.store
.enabled
) {
1621 implementations
= [];
1623 batch
= batch
.filter( function ( module
) {
1624 var implementation
= mw
.loader
.store
.get( module
);
1625 if ( implementation
) {
1626 implementations
.push( implementation
);
1627 sourceModules
.push( module
);
1632 asyncEval( implementations
, function ( err
) {
1634 // Not good, the cached mw.loader.implement calls failed! This should
1635 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1636 // Depending on how corrupt the string is, it is likely that some
1637 // modules' implement() succeeded while the ones after the error will
1638 // never run and leave their modules in the 'loading' state forever.
1639 mw
.loader
.store
.stats
.failed
++;
1641 // Since this is an error not caused by an individual module but by
1642 // something that infected the implement call itself, don't take any
1643 // risks and clear everything in this cache.
1644 mw
.loader
.store
.clear();
1646 mw
.trackError( 'resourceloader.exception', {
1648 source
: 'store-eval'
1650 // Re-add the failed ones that are still pending back to the batch
1651 failed
= sourceModules
.filter( function ( module
) {
1652 return registry
[ module
].state
=== 'loading';
1654 batchRequest( failed
);
1658 batchRequest( batch
);
1662 * Register a source.
1664 * The #work() method will use this information to split up requests by source.
1666 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1668 * @param {string|Object} id Source ID, or object mapping ids to load urls
1669 * @param {string} loadUrl Url to a load.php end point
1670 * @throws {Error} If source id is already registered
1672 addSource: function ( id
, loadUrl
) {
1674 // Allow multiple additions
1675 if ( typeof id
=== 'object' ) {
1676 for ( source
in id
) {
1677 mw
.loader
.addSource( source
, id
[ source
] );
1682 if ( hasOwn
.call( sources
, id
) ) {
1683 throw new Error( 'source already registered: ' + id
);
1686 sources
[ id
] = loadUrl
;
1690 * Register a module, letting the system know about it and its properties.
1692 * The startup modules contain calls to this method.
1694 * When using multiple module registration by passing an array, dependencies that
1695 * are specified as references to modules within the array will be resolved before
1696 * the modules are registered.
1698 * @param {string|Array} module Module name or array of arrays, each containing
1699 * a list of arguments compatible with this method
1700 * @param {string|number} version Module version hash (falls backs to empty string)
1701 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1702 * @param {string|Array} dependencies One string or array of strings of module
1703 * names on which this module depends.
1704 * @param {string} [group=null] Group which the module is in
1705 * @param {string} [source='local'] Name of the source
1706 * @param {string} [skip=null] Script body of the skip function
1708 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1710 // Allow multiple registration
1711 if ( typeof module
=== 'object' ) {
1712 resolveIndexedDependencies( module
);
1713 for ( i
= 0; i
< module
.length
; i
++ ) {
1714 // module is an array of module names
1715 if ( typeof module
[ i
] === 'string' ) {
1716 mw
.loader
.register( module
[ i
] );
1717 // module is an array of arrays
1718 } else if ( typeof module
[ i
] === 'object' ) {
1719 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1724 if ( hasOwn
.call( registry
, module
) ) {
1725 throw new Error( 'module already registered: ' + module
);
1727 if ( typeof dependencies
=== 'string' ) {
1728 // A single module name
1729 deps
= [ dependencies
];
1730 } else if ( typeof dependencies
=== 'object' ) {
1731 // Array of module names
1732 deps
= dependencies
;
1734 // List the module as registered
1735 registry
[ module
] = {
1736 // Exposed to execute() for mw.loader.implement() closures.
1737 // Import happens via require().
1741 version
: version
!== undefined ? String( version
) : '',
1742 dependencies
: deps
|| [],
1743 group
: typeof group
=== 'string' ? group
: null,
1744 source
: typeof source
=== 'string' ? source
: 'local',
1745 state
: 'registered',
1746 skip
: typeof skip
=== 'string' ? skip
: null
1751 * Implement a module given the components that make up the module.
1753 * When #load() or #using() requests one or more modules, the server
1754 * response contain calls to this function.
1756 * @param {string} module Name of module and current module version. Formatted
1757 * as '`[name]@[version]`". This version should match the requested version
1758 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1759 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1760 * @param {Function|Array|string} [script] Function with module code, list of URLs
1761 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1762 * @param {Object} [style] Should follow one of the following patterns:
1764 * { "css": [css, ..] }
1765 * { "url": { <media>: [url, ..] } }
1767 * And for backwards compatibility (needs to be supported forever due to caching):
1770 * { <media>: [url, ..] }
1772 * The reason css strings are not concatenated anymore is T33676. We now check
1773 * whether it's safe to extend the stylesheet.
1776 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1777 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1779 implement: function ( module
, script
, style
, messages
, templates
) {
1780 var split
= splitModuleKey( module
),
1782 version
= split
.version
;
1783 // Automatically register module
1784 if ( !hasOwn
.call( registry
, name
) ) {
1785 mw
.loader
.register( name
);
1787 // Check for duplicate implementation
1788 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1789 throw new Error( 'module already implemented: ' + name
);
1792 // Without this reset, if there is a version mismatch between the
1793 // requested and received module version, then mw.loader.store would
1794 // cache the response under the requested key. Thus poisoning the cache
1795 // indefinitely with a stale value. (T117587)
1796 registry
[ name
].version
= version
;
1798 // Attach components
1799 registry
[ name
].script
= script
|| null;
1800 registry
[ name
].style
= style
|| null;
1801 registry
[ name
].messages
= messages
|| null;
1802 registry
[ name
].templates
= templates
|| null;
1803 // The module may already have been marked as erroneous
1804 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1805 registry
[ name
].state
= 'loaded';
1806 if ( allReady( registry
[ name
].dependencies
) ) {
1813 * Load an external script or one or more modules.
1815 * This method takes a list of unrelated modules. Use cases:
1817 * - A web page will be composed of many different widgets. These widgets independently
1818 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1819 * have problems, or are no longer known (e.g. cached HTML), the other modules
1820 * should still be loaded.
1821 * - This method is used for preloading, which must not throw. Later code that
1822 * calls #using() will handle the error.
1824 * @param {string|Array} modules Either the name of a module, array of modules,
1825 * or a URL of an external script or style
1826 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1827 * external script or style; acceptable values are "text/css" and
1828 * "text/javascript"; if no type is provided, text/javascript is assumed.
1830 load: function ( modules
, type
) {
1833 // Allow calling with a url or single dependency as a string
1834 if ( typeof modules
=== 'string' ) {
1835 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1836 if ( /^(https?:)?\/?\//.test( modules
) ) {
1837 if ( type
=== 'text/css' ) {
1838 l
= document
.createElement( 'link' );
1839 l
.rel
= 'stylesheet';
1841 document
.head
.appendChild( l
);
1844 if ( type
=== 'text/javascript' || type
=== undefined ) {
1845 addScript( modules
);
1849 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1851 // Called with single module
1852 modules
= [ modules
];
1855 // Filter out top-level modules that are unknown or failed to load before.
1856 filtered
= modules
.filter( function ( module
) {
1857 var state
= mw
.loader
.getState( module
);
1858 return state
!== 'error' && state
!== 'missing';
1860 // Resolve remaining list using the known dependency tree.
1861 // This also filters out modules with unknown dependencies. (T36853)
1862 filtered
= resolveStubbornly( filtered
);
1863 // Some modules are not yet ready, add to module load queue.
1864 enqueue( filtered
, undefined, undefined );
1868 * Change the state of one or more modules.
1870 * @param {string|Object} module Module name or object of module name/state pairs
1871 * @param {string} state State name
1873 state: function ( module
, state
) {
1876 if ( typeof module
=== 'object' ) {
1877 for ( m
in module
) {
1878 mw
.loader
.state( m
, module
[ m
] );
1882 if ( !hasOwn
.call( registry
, module
) ) {
1883 mw
.loader
.register( module
);
1885 registry
[ module
].state
= state
;
1886 if ( state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
1887 // Make sure pending modules depending on this one get executed if their
1888 // dependencies are now fulfilled!
1889 handlePending( module
);
1894 * Get the version of a module.
1896 * @param {string} module Name of module
1897 * @return {string|null} The version, or null if the module (or its version) is not
1900 getVersion: function ( module
) {
1901 return hasOwn
.call( registry
, module
) ? registry
[ module
].version
: null;
1905 * Get the state of a module.
1907 * @param {string} module Name of module
1908 * @return {string|null} The state, or null if the module (or its state) is not
1911 getState: function ( module
) {
1912 return hasOwn
.call( registry
, module
) ? registry
[ module
].state
: null;
1916 * Get the names of all registered modules.
1920 getModuleNames: function () {
1921 return Object
.keys( registry
);
1925 * Get the exported value of a module.
1927 * This static method is publicly exposed for debugging purposes
1928 * only and must not be used in production code. In production code,
1929 * please use the dynamically provided `require()` function instead.
1931 * In case of lazy-loaded modules via mw.loader#using(), the returned
1932 * Promise provides the function, see #using() for examples.
1936 * @param {string} moduleName Module name
1937 * @return {Mixed} Exported value
1939 require: function ( moduleName
) {
1940 var state
= mw
.loader
.getState( moduleName
);
1942 // Only ready modules can be required
1943 if ( state
!== 'ready' ) {
1944 // Module may've forgotten to declare a dependency
1945 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
1948 return registry
[ moduleName
].module
.exports
;
1952 * On browsers that implement the localStorage API, the module store serves as a
1953 * smart complement to the browser cache. Unlike the browser cache, the module store
1954 * can slice a concatenated response from ResourceLoader into its constituent
1955 * modules and cache each of them separately, using each module's versioning scheme
1956 * to determine when the cache should be invalidated.
1959 * @class mw.loader.store
1962 // Whether the store is in use on this page.
1965 // Modules whose string representation exceeds 100 kB are
1966 // ineligible for storage. See bug T66721.
1967 MODULE_SIZE_MAX
: 100 * 1000,
1969 // The contents of the store, mapping '[name]@[version]' keys
1970 // to module implementations.
1974 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
1977 * Construct a JSON-serializable object representing the content of the store.
1979 * @return {Object} Module store contents.
1981 toJSON: function () {
1982 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
1986 * Get the localStorage key for the entire module store. The key references
1987 * $wgDBname to prevent clashes between wikis which share a common host.
1989 * @return {string} localStorage item key
1991 getStoreKey: function () {
1992 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
1996 * Get a key on which to vary the module cache.
1998 * @return {string} String of concatenated vary conditions.
2000 getVary: function () {
2002 mw
.config
.get( 'skin' ),
2003 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2004 mw
.config
.get( 'wgUserLanguage' )
2009 * Initialize the store.
2011 * Retrieves store from localStorage and (if successfully retrieved) decoding
2012 * the stored JSON value to a plain object.
2014 * The try / catch block is used for JSON & localStorage feature detection.
2015 * See the in-line documentation for Modernizr's localStorage feature detection
2016 * code for a full account of why we need a try / catch:
2017 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2022 if ( mw
.loader
.store
.enabled
!== null ) {
2028 // Disabled because localStorage quotas are tight and (in Firefox's case)
2029 // shared by multiple origins.
2030 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2031 /Firefox|Opera/.test( navigator
.userAgent
) ||
2033 // Disabled by configuration.
2034 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2036 // Clear any previous store to free up space. (T66721)
2037 mw
.loader
.store
.clear();
2038 mw
.loader
.store
.enabled
= false;
2041 if ( mw
.config
.get( 'debug' ) ) {
2042 // Disable module store in debug mode
2043 mw
.loader
.store
.enabled
= false;
2048 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2049 // If we get here, localStorage is available; mark enabled
2050 mw
.loader
.store
.enabled
= true;
2051 data
= JSON
.parse( raw
);
2052 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2053 mw
.loader
.store
.items
= data
.items
;
2057 mw
.trackError( 'resourceloader.exception', {
2059 source
: 'store-localstorage-init'
2063 if ( raw
=== undefined ) {
2064 // localStorage failed; disable store
2065 mw
.loader
.store
.enabled
= false;
2067 mw
.loader
.store
.update();
2072 * Retrieve a module from the store and update cache hit stats.
2074 * @param {string} module Module name
2075 * @return {string|boolean} Module implementation or false if unavailable
2077 get: function ( module
) {
2080 if ( !mw
.loader
.store
.enabled
) {
2084 key
= getModuleKey( module
);
2085 if ( key
in mw
.loader
.store
.items
) {
2086 mw
.loader
.store
.stats
.hits
++;
2087 return mw
.loader
.store
.items
[ key
];
2089 mw
.loader
.store
.stats
.misses
++;
2094 * Stringify a module and queue it for storage.
2096 * @param {string} module Module name
2097 * @param {Object} descriptor The module's descriptor as set in the registry
2098 * @return {boolean} Module was set
2100 set: function ( module
, descriptor
) {
2103 if ( !mw
.loader
.store
.enabled
) {
2107 key
= getModuleKey( module
);
2110 // Already stored a copy of this exact version
2111 key
in mw
.loader
.store
.items
||
2112 // Module failed to load
2113 descriptor
.state
!== 'ready' ||
2114 // Unversioned, private, or site-/user-specific
2115 !descriptor
.version
||
2116 descriptor
.group
=== 'private' ||
2117 descriptor
.group
=== 'user' ||
2118 // Partial descriptor
2119 // (e.g. skipped module, or style module with state=ready)
2120 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2121 descriptor
.templates
].indexOf( undefined ) !== -1
2129 JSON
.stringify( key
),
2130 typeof descriptor
.script
=== 'function' ?
2131 String( descriptor
.script
) :
2132 JSON
.stringify( descriptor
.script
),
2133 JSON
.stringify( descriptor
.style
),
2134 JSON
.stringify( descriptor
.messages
),
2135 JSON
.stringify( descriptor
.templates
)
2137 // Attempted workaround for a possible Opera bug (bug T59567).
2138 // This regex should never match under sane conditions.
2139 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2140 args
[ 1 ] = 'function' + args
[ 1 ];
2141 mw
.trackError( 'resourceloader.assert', { source
: 'bug-T59567' } );
2144 mw
.trackError( 'resourceloader.exception', {
2146 source
: 'store-localstorage-json'
2151 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2152 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2155 mw
.loader
.store
.items
[ key
] = src
;
2156 mw
.loader
.store
.update();
2161 * Iterate through the module store, removing any item that does not correspond
2162 * (in name and version) to an item in the module registry.
2164 * @return {boolean} Store was pruned
2166 prune: function () {
2169 if ( !mw
.loader
.store
.enabled
) {
2173 for ( key
in mw
.loader
.store
.items
) {
2174 module
= key
.slice( 0, key
.indexOf( '@' ) );
2175 if ( getModuleKey( module
) !== key
) {
2176 mw
.loader
.store
.stats
.expired
++;
2177 delete mw
.loader
.store
.items
[ key
];
2178 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2179 // This value predates the enforcement of a size limit on cached modules.
2180 delete mw
.loader
.store
.items
[ key
];
2187 * Clear the entire module store right now.
2189 clear: function () {
2190 mw
.loader
.store
.items
= {};
2192 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2193 } catch ( ignored
) {}
2197 * Sync in-memory store back to localStorage.
2199 * This function debounces updates. When called with a flush already pending,
2200 * the call is coalesced into the pending update. The call to
2201 * localStorage.setItem will be naturally deferred until the page is quiescent.
2203 * Because localStorage is shared by all pages from the same origin, if multiple
2204 * pages are loaded with different module sets, the possibility exists that
2205 * modules saved by one page will be clobbered by another. But the impact would
2206 * be minor and the problem would be corrected by subsequent page views.
2210 update
: ( function () {
2211 var hasPendingWrite
= false;
2213 function flushWrites() {
2215 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2219 mw
.loader
.store
.prune();
2220 key
= mw
.loader
.store
.getStoreKey();
2222 // Replacing the content of the module store might fail if the new
2223 // contents would exceed the browser's localStorage size limit. To
2224 // avoid clogging the browser with stale data, always remove the old
2225 // value before attempting to set the new one.
2226 localStorage
.removeItem( key
);
2227 data
= JSON
.stringify( mw
.loader
.store
);
2228 localStorage
.setItem( key
, data
);
2230 mw
.trackError( 'resourceloader.exception', {
2232 source
: 'store-localstorage-update'
2236 hasPendingWrite
= false;
2239 return function () {
2240 if ( !hasPendingWrite
) {
2241 hasPendingWrite
= true;
2242 mw
.requestIdleCallback( flushWrites
);
2250 // Skeleton user object, extended by the 'mediawiki.user' module.
2257 * @property {mw.Map}
2261 * @property {mw.Map}
2266 // OOUI widgets specific to MediaWiki
2271 // Attach to window and globally alias
2272 window
.mw
= window
.mediaWiki
= mw
;