2 * Base library for MediaWiki.
4 * Exposed globally as `mw`, with `mediaWiki` as alias.
7 * @alternateClassName mediaWiki
10 /* global $VARS, $CODE */
15 var mw
, StringSet
, log
,
16 hasOwn
= Object
.prototype.hasOwnProperty
,
20 * FNV132 hash function
22 * This function implements the 32-bit version of FNV-1.
23 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
24 * its output is base 36 rather than hex.
25 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
28 * @param {string} str String to hash
29 * @return {string} hash as an seven-character base 36 string
31 function fnv132( str
) {
32 /* eslint-disable no-bitwise */
33 var hash
= 0x811C9DC5,
36 for ( i
= 0; i
< str
.length
; i
++ ) {
37 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
38 hash
^= str
.charCodeAt( i
);
41 hash
= ( hash
>>> 0 ).toString( 36 );
42 while ( hash
.length
< 7 ) {
47 /* eslint-enable no-bitwise */
50 function defineFallbacks() {
51 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
52 StringSet
= window
.Set
|| ( function () {
57 function StringSet() {
58 this.set = Object
.create( null );
60 StringSet
.prototype.add = function ( value
) {
61 this.set[ value
] = true;
63 StringSet
.prototype.has = function ( value
) {
64 return value
in this.set;
71 * Alias property to the global object.
78 * @param {Mixed} value
80 function setGlobalMapValue( map
, key
, value
) {
81 map
.values
[ key
] = value
;
86 // Deprecation notice for mw.config globals (T58550, T72470)
87 map
=== mw
.config
&& 'Use mw.config instead.'
92 * Log a message to window.console, if possible.
94 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
95 * also in production mode). Gets console references in each invocation instead of caching the
96 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
99 * @param {string} topic Stream name passed by mw.track
100 * @param {Object} data Data passed by mw.track
101 * @param {Error} [data.exception]
102 * @param {string} data.source Error source
103 * @param {string} [data.module] Name of module which caused the error
105 function logError( topic
, data
) {
106 /* eslint-disable no-console */
109 source
= data
.source
,
110 module
= data
.module
,
111 console
= window
.console
;
113 if ( console
&& console
.log
) {
114 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
116 msg
+= ' in module ' + module
;
118 msg
+= ( e
? ':' : '.' );
121 // If we have an exception object, log it to the warning channel to trigger
122 // proper stacktraces in browsers that support it.
123 if ( e
&& console
.warn
) {
127 /* eslint-enable no-console */
131 * Create an object that can be read from or written to via methods that allow
132 * interaction both with single and multiple properties at once.
138 * @param {boolean} [global=false] Whether to synchronise =values to the global
139 * window object (for backwards-compatibility with mw.config; T72470). Values are
140 * copied in one direction only. Changes to globals do not reflect in the map.
142 function Map( global
) {
143 this.values
= Object
.create( null );
144 if ( global
=== true ) {
145 // Override #set to also set the global variable
146 this.set = function ( selection
, value
) {
148 if ( arguments
.length
> 1 ) {
149 if ( typeof selection
!== 'string' ) {
152 setGlobalMapValue( this, selection
, value
);
155 if ( typeof selection
=== 'object' ) {
156 for ( s
in selection
) {
157 setGlobalMapValue( this, s
, selection
[ s
] );
170 * Get the value of one or more keys.
172 * If called with no arguments, all values are returned.
174 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
175 * @param {Mixed} [fallback=null] Value for keys that don't exist.
176 * @return {Mixed|Object|null} If selection was a string, returns the value,
177 * If selection was an array, returns an object of key/values.
178 * If no selection is passed, a new object with all key/values is returned.
180 get: function ( selection
, fallback
) {
182 fallback
= arguments
.length
> 1 ? fallback
: null;
184 if ( Array
.isArray( selection
) ) {
186 for ( i
= 0; i
< selection
.length
; i
++ ) {
187 if ( typeof selection
[ i
] === 'string' ) {
188 results
[ selection
[ i
] ] = selection
[ i
] in this.values
?
189 this.values
[ selection
[ i
] ] :
196 if ( typeof selection
=== 'string' ) {
197 return selection
in this.values
?
198 this.values
[ selection
] :
202 if ( selection
=== undefined ) {
204 for ( i
in this.values
) {
205 results
[ i
] = this.values
[ i
];
210 // Invalid selection key
215 * Set one or more key/value pairs.
217 * @param {string|Object} selection Key to set value for, or object mapping keys to values
218 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
219 * @return {boolean} True on success, false on failure
221 set: function ( selection
, value
) {
223 // Use `arguments.length` because `undefined` is also a valid value.
224 if ( arguments
.length
> 1 ) {
225 if ( typeof selection
!== 'string' ) {
228 this.values
[ selection
] = value
;
231 if ( typeof selection
=== 'object' ) {
232 for ( s
in selection
) {
233 this.values
[ s
] = selection
[ s
];
241 * Check if one or more keys exist.
243 * @param {Mixed} selection Key or array of keys to check
244 * @return {boolean} True if the key(s) exist
246 exists: function ( selection
) {
248 if ( Array
.isArray( selection
) ) {
249 for ( i
= 0; i
< selection
.length
; i
++ ) {
250 if ( typeof selection
[ i
] !== 'string' || !( selection
[ i
] in this.values
) ) {
256 return typeof selection
=== 'string' && selection
in this.values
;
262 /* eslint-disable no-console */
263 log
= ( function () {
265 * Write a verbose message to the browser's console in debug mode.
267 * This method is mainly intended for verbose logging. It is a no-op in production mode.
268 * In ResourceLoader debug mode, it will use the browser's console if available, with
269 * fallback to creating a console interface in the DOM and logging messages there.
271 * See {@link mw.log} for other logging methods.
274 * @param {...string} msg Messages to output to console.
276 var log = function () {},
277 console
= window
.console
;
279 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
280 // when adding or removing mw.log methods below!
283 * Collection of methods to help log messages to the console.
290 * Write a message to the browser console's warning channel.
292 * This method is a no-op in browsers that don't implement the Console API.
294 * @param {...string} msg Messages to output to console
296 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
297 Function
.prototype.bind
.call( console
.warn
, console
) :
301 * Write a message to the browser console's error channel.
303 * Most browsers also print a stacktrace when calling this method if the
304 * argument is an Error object.
306 * This method is a no-op in browsers that don't implement the Console API.
309 * @param {...Mixed} msg Messages to output to console
311 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
312 Function
.prototype.bind
.call( console
.error
, console
) :
316 * Create a property on a host object that, when accessed, will produce
317 * a deprecation warning in the console.
319 * @param {Object} obj Host object of deprecated property
320 * @param {string} key Name of property to create in `obj`
321 * @param {Mixed} val The value this property should return when accessed
322 * @param {string} [msg] Optional text to include in the deprecation message
323 * @param {string} [logName=key] Optional custom name for the feature.
324 * This is used instead of `key` in the message and `mw.deprecate` tracking.
326 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
328 } : function ( obj
, key
, val
, msg
, logName
) {
330 function maybeLog() {
332 trace
= new Error().stack
;
334 stacks
= new StringSet();
336 if ( !stacks
.has( trace
) ) {
338 name
= logName
|| key
;
339 mw
.track( 'mw.deprecate', name
);
341 'Use of "' + name
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' )
345 // Support: Safari 5.0
346 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
347 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
349 Object
.defineProperty( obj
, key
, {
356 set: function ( newVal
) {
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
623 * @property {Array} baseModules
625 baseModules
= $VARS
.baseModules
,
628 * For #addEmbeddedCSS() and #addLink()
631 * @property {HTMLElement|null} marker
633 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
635 // For #addEmbeddedCSS()
637 rAF
= window
.requestAnimationFrame
|| setTimeout
;
640 * Create a new style element and add it to the DOM.
643 * @param {string} text CSS text
644 * @param {Node|null} [nextNode] The element where the style tag
645 * should be inserted before
646 * @return {HTMLElement} Reference to the created style element
648 function newStyleTag( text
, nextNode
) {
649 var el
= document
.createElement( 'style' );
650 el
.appendChild( document
.createTextNode( text
) );
651 if ( nextNode
&& nextNode
.parentNode
) {
652 nextNode
.parentNode
.insertBefore( el
, nextNode
);
654 document
.head
.appendChild( el
);
661 * @param {Object} cssBuffer
663 function flushCssBuffer( cssBuffer
) {
665 // Mark this object as inactive now so that further calls to addEmbeddedCSS() from
666 // the callbacks go to a new buffer instead of this one (T105973)
667 cssBuffer
.active
= false;
668 newStyleTag( cssBuffer
.cssText
, marker
);
669 for ( i
= 0; i
< cssBuffer
.callbacks
.length
; i
++ ) {
670 cssBuffer
.callbacks
[ i
]();
675 * Add a bit of CSS text to the current browser page.
677 * The creation and insertion of the `<style>` element is debounced for two reasons:
679 * - Performing the insertion before the next paint round via requestAnimationFrame
680 * avoids forced or wasted style recomputations, which are expensive in browsers.
681 * - Reduce how often new stylesheets are inserted by letting additional calls to this
682 * function accumulate into a buffer for at least one JavaScript tick. Modules are
683 * received from the server in batches, which means there is likely going to be many
684 * calls to this function in a row within the same tick / the same call stack.
688 * @param {string} cssText CSS text to be added in a `<style>` tag.
689 * @param {Function} callback Called after the insertion has occurred
691 function addEmbeddedCSS( cssText
, callback
) {
692 // Create a buffer if:
693 // - We don't have one yet.
694 // - The previous one is closed.
695 // - The next CSS chunk syntactically needs to be at the start of a stylesheet (T37562).
696 if ( !nextCssBuffer
|| nextCssBuffer
.active
=== false || cssText
.slice( 0, '@import'.length
) === '@import' ) {
704 // Linebreak for somewhat distinguishable sections
705 nextCssBuffer
.cssText
+= '\n' + cssText
;
706 nextCssBuffer
.callbacks
.push( callback
);
708 if ( nextCssBuffer
.active
=== null ) {
709 nextCssBuffer
.active
= true;
710 // The flushCssBuffer callback has its parameter bound by reference, which means
711 // 1) We can still extend the buffer from our object reference after this point.
712 // 2) We can safely re-assign the variable (not the object) to start a new buffer.
713 rAF( flushCssBuffer
.bind( null, nextCssBuffer
) );
719 * @param {Array} modules List of module names
720 * @return {string} Hash of concatenated version hashes.
722 function getCombinedVersion( modules
) {
723 var hashes
= modules
.reduce( function ( result
, module
) {
724 return result
+ registry
[ module
].version
;
726 return fnv132( hashes
);
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 direct and base dependencies are in state 'ready'
751 * @param {string} module Name of the module to be checked
752 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
754 function allWithImplicitReady( module
) {
755 return allReady( registry
[ module
].dependencies
) &&
756 ( baseModules
.indexOf( module
) !== -1 || allReady( baseModules
) );
760 * Determine whether all dependencies are in state 'ready', which means we may
761 * execute the module or job now.
764 * @param {Array} modules Names of modules to be checked
765 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
767 function anyFailed( modules
) {
769 for ( i
= 0; i
< modules
.length
; i
++ ) {
770 state
= mw
.loader
.getState( modules
[ i
] );
771 if ( state
=== 'error' || state
=== 'missing' ) {
779 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
780 * pending jobs and modules that depend upon this module. If the given module failed,
781 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
782 * all jobs/modules now having their dependencies satisfied.
784 * Jobs that depend on a failed module, will have their error callback ran (if any).
787 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
789 function handlePending( module
) {
790 var j
, job
, hasErrors
, m
, stateChange
, fromBaseModule
;
792 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
793 fromBaseModule
= baseModules
.indexOf( module
) !== -1;
794 // If the current module failed, mark all dependent modules also as failed.
795 // Iterate until steady-state to propagate the error state upwards in the
799 for ( m
in registry
) {
800 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
801 // Always propagate errors from base modules to regular modules (implicit dependency).
802 // Between base modules or regular modules, consider direct dependencies only.
804 ( fromBaseModule
&& baseModules
.indexOf( m
) === -1 ) ||
805 anyFailed( registry
[ m
].dependencies
)
807 registry
[ m
].state
= 'error';
812 } while ( stateChange
);
815 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
816 for ( j
= 0; j
< jobs
.length
; j
++ ) {
817 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
818 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
819 // All dependencies satisfied, or some have errors
825 if ( typeof job
.error
=== 'function' ) {
826 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
829 if ( typeof job
.ready
=== 'function' ) {
834 // A user-defined callback raised an exception.
835 // Swallow it to protect our state machine!
836 mw
.trackError( 'resourceloader.exception', {
839 source
: 'load-callback'
845 // The current module became 'ready'.
846 if ( registry
[ module
].state
=== 'ready' ) {
847 // Save it to the module store.
848 mw
.loader
.store
.set( module
, registry
[ module
] );
849 // Recursively execute all dependent modules that were already loaded
850 // (waiting for execution) and no longer have unsatisfied dependencies.
851 for ( m
in registry
) {
852 // Base modules may have dependencies amongst eachother to ensure correct
853 // execution order. Regular modules wait for all base modules.
854 if ( registry
[ m
].state
=== 'loaded' && allWithImplicitReady( m
) ) {
855 // eslint-disable-next-line no-use-before-define
863 * Resolve dependencies and detect circular references.
866 * @param {string} module Name of the top-level module whose dependencies shall be
867 * resolved and sorted.
868 * @param {Array} resolved Returns a topological sort of the given module and its
869 * dependencies, such that later modules depend on earlier modules. The array
870 * contains the module names. If the array contains already some module names,
871 * this function appends its result to the pre-existing array.
872 * @param {StringSet} [unresolved] Used to track the current dependency
873 * chain, and to report loops in the dependency graph.
874 * @throws {Error} If any unregistered module or a dependency loop is encountered
876 function sortDependencies( module
, resolved
, unresolved
) {
879 if ( !hasOwn
.call( registry
, module
) ) {
880 throw new Error( 'Unknown dependency: ' + module
);
883 if ( registry
[ module
].skip
!== null ) {
884 // eslint-disable-next-line no-new-func
885 skip
= new Function( registry
[ module
].skip
);
886 registry
[ module
].skip
= null;
888 registry
[ module
].skipped
= true;
889 registry
[ module
].dependencies
= [];
890 registry
[ module
].state
= 'ready';
891 handlePending( module
);
896 if ( resolved
.indexOf( module
) !== -1 ) {
897 // Module already resolved; nothing to do
900 // Create unresolved if not passed in
902 unresolved
= new StringSet();
906 if ( baseModules
.indexOf( module
) === -1 ) {
907 baseModules
.forEach( function ( baseModule
) {
908 if ( resolved
.indexOf( baseModule
) === -1 ) {
909 resolved
.push( baseModule
);
914 // Tracks down dependencies
915 deps
= registry
[ module
].dependencies
;
916 unresolved
.add( module
);
917 for ( i
= 0; i
< deps
.length
; i
++ ) {
918 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
919 if ( unresolved
.has( deps
[ i
] ) ) {
921 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
925 sortDependencies( deps
[ i
], resolved
, unresolved
);
928 resolved
.push( module
);
932 * Get names of module that a module depends on, in their proper dependency order.
935 * @param {string[]} modules Array of string module names
936 * @return {Array} List of dependencies, including 'module'.
937 * @throws {Error} If an unregistered module or a dependency loop is encountered
939 function resolve( modules
) {
940 var i
, resolved
= [];
941 for ( i
= 0; i
< modules
.length
; i
++ ) {
942 sortDependencies( modules
[ i
], resolved
);
948 * Like #resolve(), except it will silently ignore modules that
949 * are missing or have missing dependencies.
952 * @param {string[]} modules Array of string module names
953 * @return {Array} List of dependencies.
955 function resolveStubbornly( modules
) {
956 var i
, saved
, resolved
= [];
957 for ( i
= 0; i
< modules
.length
; i
++ ) {
958 saved
= resolved
.slice();
960 sortDependencies( modules
[ i
], resolved
);
962 // This module is unknown or has unknown dependencies.
963 // Undo any incomplete resolutions made and keep going.
965 mw
.trackError( 'resourceloader.exception', {
975 * Load and execute a script.
978 * @param {string} src URL to script, will be used as the src attribute in the script tag
979 * @param {Function} [callback] Callback to run after request resolution
981 function addScript( src
, callback
) {
982 var script
= document
.createElement( 'script' );
984 script
.onload
= script
.onerror = function () {
985 if ( script
.parentNode
) {
986 script
.parentNode
.removeChild( script
);
994 document
.head
.appendChild( script
);
998 * Queue the loading and execution of a script for a particular module.
1000 * This does for debug mode what runScript() does for production.
1003 * @param {string} src URL of the script
1004 * @param {string} moduleName Name of currently executing module
1005 * @param {Function} callback Callback to run after addScript() resolution
1007 function queueModuleScript( src
, moduleName
, callback
) {
1008 pendingRequests
.push( function () {
1009 // Keep in sync with execute()/runScript().
1010 if ( moduleName
!== 'jquery' && hasOwn
.call( registry
, moduleName
) ) {
1011 window
.require
= mw
.loader
.require
;
1012 window
.module
= registry
[ moduleName
].module
;
1014 addScript( src
, function () {
1015 // 'module.exports' should not persist after the file is executed to
1016 // avoid leakage to unrelated code. 'require' should be kept, however,
1017 // as asynchronous access to 'require' is allowed and expected. (T144879)
1018 delete window
.module
;
1020 // Start the next one (if any)
1021 if ( pendingRequests
[ 0 ] ) {
1022 pendingRequests
.shift()();
1024 handlingPendingRequests
= false;
1028 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1029 handlingPendingRequests
= true;
1030 pendingRequests
.shift()();
1035 * Utility function for execute()
1038 * @param {string} [media] Media attribute
1039 * @param {string} url URL
1041 function addLink( media
, url
) {
1042 var el
= document
.createElement( 'link' );
1044 el
.rel
= 'stylesheet';
1045 if ( media
&& media
!== 'all' ) {
1048 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1049 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1052 if ( marker
&& marker
.parentNode
) {
1053 marker
.parentNode
.insertBefore( el
, marker
);
1055 document
.head
.appendChild( el
);
1061 * @param {string} code JavaScript code
1063 function domEval( code
) {
1064 var script
= document
.createElement( 'script' );
1065 if ( mw
.config
.get( 'wgCSPNonce' ) !== false ) {
1066 script
.nonce
= mw
.config
.get( 'wgCSPNonce' );
1069 document
.head
.appendChild( script
);
1070 script
.parentNode
.removeChild( script
);
1074 * Add one or more modules to the module load queue.
1079 * @param {string[]} dependencies Array of module names in the registry
1080 * @param {Function} [ready] Callback to execute when all dependencies are ready
1081 * @param {Function} [error] Callback to execute when any dependency fails
1083 function enqueue( dependencies
, ready
, error
) {
1084 if ( allReady( dependencies
) ) {
1085 // Run ready immediately
1086 if ( ready
!== undefined ) {
1092 if ( anyFailed( dependencies
) ) {
1093 if ( error
!== undefined ) {
1094 // Execute error immediately if any dependencies have errors
1096 new Error( 'One or more dependencies failed to load' ),
1103 // Not all dependencies are ready, add to the load queue...
1105 // Add ready and error callbacks if they were given
1106 if ( ready
!== undefined || error
!== undefined ) {
1108 // Narrow down the list to modules that are worth waiting for
1109 dependencies
: dependencies
.filter( function ( module
) {
1110 var state
= registry
[ module
].state
;
1111 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1118 dependencies
.forEach( function ( module
) {
1119 // Only queue modules that are still in the initial 'registered' state
1120 // (not ones already loading, ready or error).
1121 if ( registry
[ module
].state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1122 // Private modules must be embedded in the page. Don't bother queuing
1123 // these as the server will deny them anyway (T101806).
1124 if ( registry
[ module
].group
=== 'private' ) {
1125 registry
[ module
].state
= 'error';
1126 handlePending( module
);
1129 queue
.push( module
);
1137 * Executes a loaded module, making it ready to use
1140 * @param {string} module Module name to execute
1142 function execute( module
) {
1143 var key
, value
, media
, i
, urls
, cssHandle
, siteDeps
, siteDepErr
, runScript
,
1146 if ( !hasOwn
.call( registry
, module
) ) {
1147 throw new Error( 'Module has not been registered yet: ' + module
);
1149 if ( registry
[ module
].state
!== 'loaded' ) {
1150 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1153 registry
[ module
].state
= 'executing';
1154 $CODE
.profileExecuteStart();
1156 runScript = function () {
1157 var script
, markModuleReady
, nestedAddScript
;
1159 $CODE
.profileScriptStart();
1160 script
= registry
[ module
].script
;
1161 markModuleReady = function () {
1162 $CODE
.profileScriptEnd();
1163 registry
[ module
].state
= 'ready';
1164 handlePending( module
);
1166 nestedAddScript = function ( arr
, callback
, i
) {
1167 // Recursively call queueModuleScript() in its own callback
1168 // for each element of arr.
1169 if ( i
>= arr
.length
) {
1170 // We're at the end of the array
1175 queueModuleScript( arr
[ i
], module
, function () {
1176 nestedAddScript( arr
, callback
, i
+ 1 );
1181 if ( Array
.isArray( script
) ) {
1182 nestedAddScript( script
, markModuleReady
, 0 );
1183 } else if ( typeof script
=== 'function' ) {
1184 // Keep in sync with queueModuleScript() for debug mode
1185 if ( module
=== 'jquery' ) {
1186 // This is a special case for when 'jquery' itself is being loaded.
1187 // - The standard jquery.js distribution does not set `window.jQuery`
1188 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1189 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1190 // in a CommonJS-compatible environment, will use require('jquery'),
1191 // but that can't work when we're still inside that module.
1194 // Pass jQuery twice so that the signature of the closure which wraps
1195 // the script can bind both '$' and 'jQuery'.
1196 script( window
.$, window
.$, mw
.loader
.require
, registry
[ module
].module
);
1200 } else if ( typeof script
=== 'string' ) {
1201 // Site and user modules are legacy scripts that run in the global scope.
1202 // This is transported as a string instead of a function to avoid needing
1203 // to use string manipulation to undo the function wrapper.
1208 // Module without script
1212 // Use mw.track instead of mw.log because these errors are common in production mode
1213 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1214 registry
[ module
].state
= 'error';
1215 $CODE
.profileScriptEnd();
1216 mw
.trackError( 'resourceloader.exception', {
1217 exception
: e
, module
:
1218 module
, source
: 'module-execute'
1220 handlePending( module
);
1224 // Add localizations to message system
1225 if ( registry
[ module
].messages
) {
1226 mw
.messages
.set( registry
[ module
].messages
);
1229 // Initialise templates
1230 if ( registry
[ module
].templates
) {
1231 mw
.templates
.set( module
, registry
[ module
].templates
);
1234 // Adding of stylesheets is asynchronous via addEmbeddedCSS().
1235 // The below function uses a counting semaphore to make sure we don't call
1236 // runScript() until after this module's stylesheets have been inserted
1238 cssHandle = function () {
1239 // Increase semaphore, when creating a callback for addEmbeddedCSS.
1241 return function () {
1243 // Decrease semaphore, when said callback is invoked.
1245 if ( cssPending
=== 0 ) {
1247 // This callback is exposed to addEmbeddedCSS, which is outside the execute()
1248 // function and is not concerned with state-machine integrity. In turn,
1249 // addEmbeddedCSS() actually exposes stuff further into the browser (rAF).
1250 // If increment and decrement callbacks happen in the wrong order, or start
1251 // again afterwards, then this branch could be reached multiple times.
1252 // To protect the integrity of the state-machine, prevent that from happening
1253 // by making runScript() cannot be called more than once. We store a private
1254 // reference when we first reach this branch, then deference the original, and
1255 // call our reference to it.
1256 runScriptCopy
= runScript
;
1257 runScript
= undefined;
1263 // Process styles (see also mw.loader.implement)
1264 // * back-compat: { <media>: css }
1265 // * back-compat: { <media>: [url, ..] }
1266 // * { "css": [css, ..] }
1267 // * { "url": { <media>: [url, ..] } }
1268 if ( registry
[ module
].style
) {
1269 for ( key
in registry
[ module
].style
) {
1270 value
= registry
[ module
].style
[ key
];
1273 if ( key
!== 'url' && key
!== 'css' ) {
1274 // Backwards compatibility, key is a media-type
1275 if ( typeof value
=== 'string' ) {
1276 // back-compat: { <media>: css }
1277 // Ignore 'media' because it isn't supported (nor was it used).
1278 // Strings are pre-wrapped in "@media". The media-type was just ""
1279 // (because it had to be set to something).
1280 // This is one of the reasons why this format is no longer used.
1281 addEmbeddedCSS( value
, cssHandle() );
1283 // back-compat: { <media>: [url, ..] }
1289 // Array of css strings in key 'css',
1290 // or back-compat array of urls from media-type
1291 if ( Array
.isArray( value
) ) {
1292 for ( i
= 0; i
< value
.length
; i
++ ) {
1293 if ( key
=== 'bc-url' ) {
1294 // back-compat: { <media>: [url, ..] }
1295 addLink( media
, value
[ i
] );
1296 } else if ( key
=== 'css' ) {
1297 // { "css": [css, ..] }
1298 addEmbeddedCSS( value
[ i
], cssHandle() );
1301 // Not an array, but a regular object
1302 // Array of urls inside media-type key
1303 } else if ( typeof value
=== 'object' ) {
1304 // { "url": { <media>: [url, ..] } }
1305 for ( media
in value
) {
1306 urls
= value
[ media
];
1307 for ( i
= 0; i
< urls
.length
; i
++ ) {
1308 addLink( media
, urls
[ i
] );
1315 // End profiling of execute()-self before we call runScript(),
1316 // which we want to measure separately without overlap.
1317 $CODE
.profileExecuteEnd();
1319 if ( module
=== 'user' ) {
1320 // Implicit dependency on the site module. Not a real dependency because it should
1321 // run after 'site' regardless of whether it succeeds or fails.
1322 // Note: This is a simplified version of mw.loader.using(), inlined here because
1323 // mw.loader.using() is part of mediawiki.base (depends on jQuery; T192623).
1325 siteDeps
= resolve( [ 'site' ] );
1330 if ( siteDepErr
=== undefined ) {
1331 enqueue( siteDeps
, runScript
, runScript
);
1333 } else if ( cssPending
=== 0 ) {
1334 // Regular module without styles
1337 // else: runScript will get called via cssHandle()
1340 function sortQuery( o
) {
1349 for ( key
= 0; key
< a
.length
; key
++ ) {
1350 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1356 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1357 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1359 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1360 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1362 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1363 * because its implementation needs to keep track of potential string size in order
1364 * to decide when to split the requests due to url size.
1367 * @param {Object} moduleMap Module map
1369 * @return {string} return.str Module query string
1370 * @return {Array} return.list List of module names in matching order
1372 function buildModulesString( moduleMap
) {
1377 function restore( suffix
) {
1381 for ( prefix
in moduleMap
) {
1382 p
= prefix
=== '' ? '' : prefix
+ '.';
1383 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1384 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1387 str
: str
.join( '|' ),
1393 * Resolve indexed dependencies.
1395 * ResourceLoader uses an optimization to save space which replaces module names in
1396 * dependency lists with the index of that module within the array of module
1397 * registration data if it exists. The benefit is a significant reduction in the data
1398 * size of the startup module. This function changes those dependency lists back to
1399 * arrays of strings.
1402 * @param {Array} modules Modules array
1404 function resolveIndexedDependencies( modules
) {
1406 function resolveIndex( dep
) {
1407 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1409 for ( i
= 0; i
< modules
.length
; i
++ ) {
1410 deps
= modules
[ i
][ 2 ];
1412 for ( j
= 0; j
< deps
.length
; j
++ ) {
1413 deps
[ j
] = resolveIndex( deps
[ j
] );
1421 * @param {Object} params Map of parameter names to values
1424 function makeQueryString( params
) {
1425 return Object
.keys( params
).map( function ( key
) {
1426 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1431 * Create network requests for a batch of modules.
1433 * This is an internal method for #work(). This must not be called directly
1434 * unless the modules are already registered, and no request is in progress,
1435 * and the module state has already been set to `loading`.
1438 * @param {string[]} batch
1440 function batchRequest( batch
) {
1441 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
,
1442 source
, group
, i
, modules
, sourceLoadScript
,
1443 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1444 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1447 * Start the currently drafted request to the server.
1451 function doRequest() {
1452 // Optimisation: Inherit (Object.create), not copy ($.extend)
1453 var query
= Object
.create( currReqBase
),
1454 packed
= buildModulesString( moduleMap
);
1455 query
.modules
= packed
.str
;
1456 // The packing logic can change the effective order, even if the input was
1457 // sorted. As such, the call to getCombinedVersion() must use this
1458 // effective order, instead of currReqModules, as otherwise the combined
1459 // version will not match the hash expected by the server based on
1460 // combining versions from the module query string in-order. (T188076)
1461 query
.version
= getCombinedVersion( packed
.list
);
1462 query
= sortQuery( query
);
1463 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1466 if ( !batch
.length
) {
1470 // Always order modules alphabetically to help reduce cache
1471 // misses for otherwise identical content.
1474 // Query parameters common to all requests
1476 skin
: mw
.config
.get( 'skin' ),
1477 lang
: mw
.config
.get( 'wgUserLanguage' ),
1478 debug
: mw
.config
.get( 'debug' )
1480 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1482 // Split module list by source and by group.
1483 splits
= Object
.create( null );
1484 for ( b
= 0; b
< batch
.length
; b
++ ) {
1485 bSource
= registry
[ batch
[ b
] ].source
;
1486 bGroup
= registry
[ batch
[ b
] ].group
;
1487 if ( !splits
[ bSource
] ) {
1488 splits
[ bSource
] = Object
.create( null );
1490 if ( !splits
[ bSource
][ bGroup
] ) {
1491 splits
[ bSource
][ bGroup
] = [];
1493 splits
[ bSource
][ bGroup
].push( batch
[ b
] );
1496 for ( source
in splits
) {
1497 sourceLoadScript
= sources
[ source
];
1499 for ( group
in splits
[ source
] ) {
1501 // Cache access to currently selected list of
1502 // modules for this group from this source.
1503 modules
= splits
[ source
][ group
];
1505 // Query parameters common to requests for this module group
1506 // Optimisation: Inherit (Object.create), not copy ($.extend)
1507 currReqBase
= Object
.create( reqBase
);
1508 // User modules require a user name in the query string.
1509 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1510 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1513 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1514 // > '&modules='.length === 9
1515 // > '&version=1234567'.length === 16
1517 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1519 // We may need to split up the request to honor the query string length limit,
1520 // so build it piece by piece.
1521 l
= currReqBaseLength
;
1522 moduleMap
= Object
.create( null ); // { prefix: [ suffixes ] }
1523 currReqModules
= [];
1525 for ( i
= 0; i
< modules
.length
; i
++ ) {
1526 // Determine how many bytes this module would add to the query string
1527 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1528 // If lastDotIndex is -1, substr() returns an empty string
1529 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1530 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1531 bytesAdded
= moduleMap
[ prefix
] ?
1532 suffix
.length
+ 3 : // '%2C'.length == 3
1533 modules
[ i
].length
+ 3; // '%7C'.length == 3
1535 // If the url would become too long, create a new one, but don't create empty requests
1536 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1537 // Dispatch what we've got...
1539 // .. and start again.
1540 l
= currReqBaseLength
;
1541 moduleMap
= Object
.create( null );
1542 currReqModules
= [];
1544 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1546 if ( !moduleMap
[ prefix
] ) {
1547 moduleMap
[ prefix
] = [];
1550 moduleMap
[ prefix
].push( suffix
);
1551 currReqModules
.push( modules
[ i
] );
1553 // If there's anything left in moduleMap, request that too
1554 if ( currReqModules
.length
) {
1563 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1564 * form of calls to mw.loader#implement().
1565 * @param {Function} cb Callback in case of failure
1566 * @param {Error} cb.err
1568 function asyncEval( implementations
, cb
) {
1569 if ( !implementations
.length
) {
1572 mw
.requestIdleCallback( function () {
1574 domEval( implementations
.join( ';' ) );
1582 * Make a versioned key for a specific module.
1585 * @param {string} module Module name
1586 * @return {string|null} Module key in format '`[name]@[version]`',
1587 * or null if the module does not exist
1589 function getModuleKey( module
) {
1590 return hasOwn
.call( registry
, module
) ?
1591 ( module
+ '@' + registry
[ module
].version
) : null;
1596 * @param {string} key Module name or '`[name]@[version]`'
1599 function splitModuleKey( key
) {
1600 var index
= key
.indexOf( '@' );
1601 if ( index
=== -1 ) {
1608 name
: key
.slice( 0, index
),
1609 version
: key
.slice( index
+ 1 )
1613 /* Public Members */
1616 * The module registry is exposed as an aid for debugging and inspecting page
1617 * state; it is not a public interface for modifying the registry.
1623 moduleRegistry
: registry
,
1626 * @inheritdoc #newStyleTag
1629 addStyleTag
: newStyleTag
,
1636 * Start loading of all queued module dependencies.
1641 var q
, batch
, implementations
, sourceModules
;
1645 // Appends a list of modules from the queue to the batch
1646 for ( q
= 0; q
< queue
.length
; q
++ ) {
1647 // Only load modules which are registered
1648 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1649 // Prevent duplicate entries
1650 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1651 batch
.push( queue
[ q
] );
1652 // Mark registered modules as loading
1653 registry
[ queue
[ q
] ].state
= 'loading';
1658 // Now that the queue has been processed into a batch, clear the queue.
1659 // This MUST happen before we initiate any eval or network request. Otherwise,
1660 // it is possible for a cached script to instantly trigger the same work queue
1661 // again; all before we've cleared it causing each request to include modules
1662 // which are already loaded.
1665 if ( !batch
.length
) {
1669 mw
.loader
.store
.init();
1670 if ( mw
.loader
.store
.enabled
) {
1671 implementations
= [];
1673 batch
= batch
.filter( function ( module
) {
1674 var implementation
= mw
.loader
.store
.get( module
);
1675 if ( implementation
) {
1676 implementations
.push( implementation
);
1677 sourceModules
.push( module
);
1682 asyncEval( implementations
, function ( err
) {
1684 // Not good, the cached mw.loader.implement calls failed! This should
1685 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1686 // Depending on how corrupt the string is, it is likely that some
1687 // modules' implement() succeeded while the ones after the error will
1688 // never run and leave their modules in the 'loading' state forever.
1689 mw
.loader
.store
.stats
.failed
++;
1691 // Since this is an error not caused by an individual module but by
1692 // something that infected the implement call itself, don't take any
1693 // risks and clear everything in this cache.
1694 mw
.loader
.store
.clear();
1696 mw
.trackError( 'resourceloader.exception', {
1698 source
: 'store-eval'
1700 // Re-add the failed ones that are still pending back to the batch
1701 failed
= sourceModules
.filter( function ( module
) {
1702 return registry
[ module
].state
=== 'loading';
1704 batchRequest( failed
);
1708 batchRequest( batch
);
1712 * Register a source.
1714 * The #work() method will use this information to split up requests by source.
1716 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1718 * @param {string|Object} id Source ID, or object mapping ids to load urls
1719 * @param {string} loadUrl Url to a load.php end point
1720 * @throws {Error} If source id is already registered
1722 addSource: function ( id
, loadUrl
) {
1724 // Allow multiple additions
1725 if ( typeof id
=== 'object' ) {
1726 for ( source
in id
) {
1727 mw
.loader
.addSource( source
, id
[ source
] );
1732 if ( hasOwn
.call( sources
, id
) ) {
1733 throw new Error( 'source already registered: ' + id
);
1736 sources
[ id
] = loadUrl
;
1740 * Register a module, letting the system know about it and its properties.
1742 * The startup modules contain calls to this method.
1744 * When using multiple module registration by passing an array, dependencies that
1745 * are specified as references to modules within the array will be resolved before
1746 * the modules are registered.
1748 * @param {string|Array} module Module name or array of arrays, each containing
1749 * a list of arguments compatible with this method
1750 * @param {string|number} version Module version hash (falls backs to empty string)
1751 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1752 * @param {string[]} [dependencies] Array of module names on which this module depends.
1753 * @param {string} [group=null] Group which the module is in
1754 * @param {string} [source='local'] Name of the source
1755 * @param {string} [skip=null] Script body of the skip function
1757 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1759 // Allow multiple registration
1760 if ( typeof module
=== 'object' ) {
1761 resolveIndexedDependencies( module
);
1762 // module is an array of arrays
1763 for ( i
= 0; i
< module
.length
; i
++ ) {
1764 // module is an array of module names
1765 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1769 if ( hasOwn
.call( registry
, module
) ) {
1770 throw new Error( 'module already registered: ' + module
);
1772 // List the module as registered
1773 registry
[ module
] = {
1774 // Exposed to execute() for mw.loader.implement() closures.
1775 // Import happens via require().
1779 version
: String( version
|| '' ),
1780 dependencies
: dependencies
|| [],
1781 group
: typeof group
=== 'string' ? group
: null,
1782 source
: typeof source
=== 'string' ? source
: 'local',
1783 state
: 'registered',
1784 skip
: typeof skip
=== 'string' ? skip
: null
1789 * Implement a module given the components that make up the module.
1791 * When #load() or #using() requests one or more modules, the server
1792 * response contain calls to this function.
1794 * @param {string} module Name of module and current module version. Formatted
1795 * as '`[name]@[version]`". This version should match the requested version
1796 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1797 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1798 * @param {Function|Array|string} [script] Function with module code, list of URLs
1799 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1800 * @param {Object} [style] Should follow one of the following patterns:
1802 * { "css": [css, ..] }
1803 * { "url": { <media>: [url, ..] } }
1805 * And for backwards compatibility (needs to be supported forever due to caching):
1808 * { <media>: [url, ..] }
1810 * The reason css strings are not concatenated anymore is T33676. We now check
1811 * whether it's safe to extend the stylesheet.
1814 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1815 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1817 implement: function ( module
, script
, style
, messages
, templates
) {
1818 var split
= splitModuleKey( module
),
1820 version
= split
.version
;
1821 // Automatically register module
1822 if ( !hasOwn
.call( registry
, name
) ) {
1823 mw
.loader
.register( name
);
1825 // Check for duplicate implementation
1826 if ( registry
[ name
].script
!== undefined ) {
1827 throw new Error( 'module already implemented: ' + name
);
1830 // Without this reset, if there is a version mismatch between the
1831 // requested and received module version, then mw.loader.store would
1832 // cache the response under the requested key. Thus poisoning the cache
1833 // indefinitely with a stale value. (T117587)
1834 registry
[ name
].version
= version
;
1836 // Attach components
1837 registry
[ name
].script
= script
|| null;
1838 registry
[ name
].style
= style
|| null;
1839 registry
[ name
].messages
= messages
|| null;
1840 registry
[ name
].templates
= templates
|| null;
1841 // The module may already have been marked as erroneous
1842 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1843 registry
[ name
].state
= 'loaded';
1844 if ( allWithImplicitReady( name
) ) {
1851 * Load an external script or one or more modules.
1853 * This method takes a list of unrelated modules. Use cases:
1855 * - A web page will be composed of many different widgets. These widgets independently
1856 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1857 * have problems, or are no longer known (e.g. cached HTML), the other modules
1858 * should still be loaded.
1859 * - This method is used for preloading, which must not throw. Later code that
1860 * calls #using() will handle the error.
1862 * @param {string|Array} modules Either the name of a module, array of modules,
1863 * or a URL of an external script or style
1864 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1865 * external script or style; acceptable values are "text/css" and
1866 * "text/javascript"; if no type is provided, text/javascript is assumed.
1868 load: function ( modules
, type
) {
1871 // Allow calling with a url or single dependency as a string
1872 if ( typeof modules
=== 'string' ) {
1873 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1874 if ( /^(https?:)?\/?\//.test( modules
) ) {
1875 if ( type
=== 'text/css' ) {
1876 l
= document
.createElement( 'link' );
1877 l
.rel
= 'stylesheet';
1879 document
.head
.appendChild( l
);
1882 if ( type
=== 'text/javascript' || type
=== undefined ) {
1883 addScript( modules
);
1887 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1889 // Called with single module
1890 modules
= [ modules
];
1893 // Filter out top-level modules that are unknown or failed to load before.
1894 filtered
= modules
.filter( function ( module
) {
1895 var state
= mw
.loader
.getState( module
);
1896 return state
!== 'error' && state
!== 'missing';
1898 // Resolve remaining list using the known dependency tree.
1899 // This also filters out modules with unknown dependencies. (T36853)
1900 filtered
= resolveStubbornly( filtered
);
1901 // Some modules are not yet ready, add to module load queue.
1902 enqueue( filtered
, undefined, undefined );
1906 * Change the state of one or more modules.
1908 * @param {Object} modules Object of module name/state pairs
1910 state: function ( modules
) {
1912 for ( module
in modules
) {
1913 state
= modules
[ module
];
1914 if ( !hasOwn
.call( registry
, module
) ) {
1915 mw
.loader
.register( module
);
1917 registry
[ module
].state
= state
;
1918 if ( state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
1919 // Make sure pending modules depending on this one get executed if their
1920 // dependencies are now fulfilled!
1921 handlePending( module
);
1927 * Get the version of a module.
1929 * @param {string} module Name of module
1930 * @return {string|null} The version, or null if the module (or its version) is not
1933 getVersion: function ( module
) {
1934 return hasOwn
.call( registry
, module
) ? registry
[ module
].version
: null;
1938 * Get the state of a module.
1940 * @param {string} module Name of module
1941 * @return {string|null} The state, or null if the module (or its state) is not
1944 getState: function ( module
) {
1945 return hasOwn
.call( registry
, module
) ? registry
[ module
].state
: null;
1949 * Get the names of all registered modules.
1953 getModuleNames: function () {
1954 return Object
.keys( registry
);
1958 * Get the exported value of a module.
1960 * This static method is publicly exposed for debugging purposes
1961 * only and must not be used in production code. In production code,
1962 * please use the dynamically provided `require()` function instead.
1964 * In case of lazy-loaded modules via mw.loader#using(), the returned
1965 * Promise provides the function, see #using() for examples.
1969 * @param {string} moduleName Module name
1970 * @return {Mixed} Exported value
1972 require: function ( moduleName
) {
1973 var state
= mw
.loader
.getState( moduleName
);
1975 // Only ready modules can be required
1976 if ( state
!== 'ready' ) {
1977 // Module may've forgotten to declare a dependency
1978 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
1981 return registry
[ moduleName
].module
.exports
;
1985 * On browsers that implement the localStorage API, the module store serves as a
1986 * smart complement to the browser cache. Unlike the browser cache, the module store
1987 * can slice a concatenated response from ResourceLoader into its constituent
1988 * modules and cache each of them separately, using each module's versioning scheme
1989 * to determine when the cache should be invalidated.
1993 * @class mw.loader.store
1996 // Whether the store is in use on this page.
1999 // Modules whose string representation exceeds 100 kB are
2000 // ineligible for storage. See bug T66721.
2001 MODULE_SIZE_MAX
: 100 * 1000,
2003 // The contents of the store, mapping '[name]@[version]' keys
2004 // to module implementations.
2008 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2011 * Construct a JSON-serializable object representing the content of the store.
2013 * @return {Object} Module store contents.
2015 toJSON: function () {
2016 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2020 * Get the localStorage key for the entire module store. The key references
2021 * $wgDBname to prevent clashes between wikis which share a common host.
2023 * @return {string} localStorage item key
2025 getStoreKey: function () {
2026 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2030 * Get a key on which to vary the module cache.
2032 * @return {string} String of concatenated vary conditions.
2034 getVary: function () {
2035 return mw
.config
.get( 'skin' ) + ':' +
2036 mw
.config
.get( 'wgResourceLoaderStorageVersion' ) + ':' +
2037 mw
.config
.get( 'wgUserLanguage' );
2041 * Initialize the store.
2043 * Retrieves store from localStorage and (if successfully retrieved) decoding
2044 * the stored JSON value to a plain object.
2046 * The try / catch block is used for JSON & localStorage feature detection.
2047 * See the in-line documentation for Modernizr's localStorage feature detection
2048 * code for a full account of why we need a try / catch:
2049 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2054 if ( this.enabled
!== null ) {
2060 // Disabled because localStorage quotas are tight and (in Firefox's case)
2061 // shared by multiple origins.
2062 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2063 /Firefox|Opera/.test( navigator
.userAgent
) ||
2065 // Disabled by configuration.
2066 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2068 // Clear any previous store to free up space. (T66721)
2070 this.enabled
= false;
2073 if ( mw
.config
.get( 'debug' ) ) {
2074 // Disable module store in debug mode
2075 this.enabled
= false;
2080 // This a string we stored, or `null` if the key does not (yet) exist.
2081 raw
= localStorage
.getItem( this.getStoreKey() );
2082 // If we get here, localStorage is available; mark enabled
2083 this.enabled
= true;
2084 // If null, JSON.parse() will cast to string and re-parse, still null.
2085 data
= JSON
.parse( raw
);
2086 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== this.getVary() ) {
2087 this.items
= data
.items
;
2091 mw
.trackError( 'resourceloader.exception', {
2093 source
: 'store-localstorage-init'
2097 // If we get here, one of four things happened:
2099 // 1. localStorage did not contain our store key.
2100 // This means `raw` is `null`, and we're on a fresh page view (cold cache).
2101 // The store was enabled, and `items` starts fresh.
2103 // 2. localStorage contained parseable data under our store key,
2104 // but it's not applicable to our current context (see getVary).
2105 // The store was enabled, and `items` starts fresh.
2107 // 3. JSON.parse threw (localStorage contained corrupt data).
2108 // This means `raw` contains a string.
2109 // The store was enabled, and `items` starts fresh.
2111 // 4. localStorage threw (disabled or otherwise unavailable).
2112 // This means `raw` was never assigned.
2113 // We will disable the store below.
2114 if ( raw
=== undefined ) {
2115 // localStorage failed; disable store
2116 this.enabled
= false;
2121 * Retrieve a module from the store and update cache hit stats.
2123 * @param {string} module Module name
2124 * @return {string|boolean} Module implementation or false if unavailable
2126 get: function ( module
) {
2129 if ( !this.enabled
) {
2133 key
= getModuleKey( module
);
2134 if ( key
in this.items
) {
2136 return this.items
[ key
];
2138 this.stats
.misses
++;
2143 * Stringify a module and queue it for storage.
2145 * @param {string} module Module name
2146 * @param {Object} descriptor The module's descriptor as set in the registry
2148 set: function ( module
, descriptor
) {
2151 if ( !this.enabled
) {
2155 key
= getModuleKey( module
);
2158 // Already stored a copy of this exact version
2159 key
in this.items
||
2160 // Module failed to load
2161 descriptor
.state
!== 'ready' ||
2162 // Unversioned, private, or site-/user-specific
2163 !descriptor
.version
||
2164 descriptor
.group
=== 'private' ||
2165 descriptor
.group
=== 'user' ||
2166 // Partial descriptor
2167 // (e.g. skipped module, or style module with state=ready)
2168 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2169 descriptor
.templates
].indexOf( undefined ) !== -1
2177 JSON
.stringify( key
),
2178 typeof descriptor
.script
=== 'function' ?
2179 String( descriptor
.script
) :
2180 JSON
.stringify( descriptor
.script
),
2181 JSON
.stringify( descriptor
.style
),
2182 JSON
.stringify( descriptor
.messages
),
2183 JSON
.stringify( descriptor
.templates
)
2186 mw
.trackError( 'resourceloader.exception', {
2188 source
: 'store-localstorage-json'
2193 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2194 if ( src
.length
> this.MODULE_SIZE_MAX
) {
2197 this.items
[ key
] = src
;
2202 * Iterate through the module store, removing any item that does not correspond
2203 * (in name and version) to an item in the module registry.
2205 prune: function () {
2208 for ( key
in this.items
) {
2209 module
= key
.slice( 0, key
.indexOf( '@' ) );
2210 if ( getModuleKey( module
) !== key
) {
2211 this.stats
.expired
++;
2212 delete this.items
[ key
];
2213 } else if ( this.items
[ key
].length
> this.MODULE_SIZE_MAX
) {
2214 // This value predates the enforcement of a size limit on cached modules.
2215 delete this.items
[ key
];
2221 * Clear the entire module store right now.
2223 clear: function () {
2226 localStorage
.removeItem( this.getStoreKey() );
2231 * Sync in-memory store back to localStorage.
2233 * This function debounces updates. When called with a flush already pending, the
2234 * scheduled flush is postponed. The call to localStorage.setItem will be keep
2235 * being deferred until the page is quiescent for 2 seconds.
2237 * Because localStorage is shared by all pages from the same origin, if multiple
2238 * pages are loaded with different module sets, the possibility exists that
2239 * modules saved by one page will be clobbered by another. The only impact of this
2240 * is minor (merely a less efficient cache use) and the problem would be corrected
2241 * by subsequent page views.
2245 update
: ( function () {
2246 var timer
, hasPendingWrites
= false;
2248 function flushWrites() {
2250 if ( !mw
.loader
.store
.enabled
) {
2254 mw
.loader
.store
.prune();
2255 key
= mw
.loader
.store
.getStoreKey();
2257 // Replacing the content of the module store might fail if the new
2258 // contents would exceed the browser's localStorage size limit. To
2259 // avoid clogging the browser with stale data, always remove the old
2260 // value before attempting to set the new one.
2261 localStorage
.removeItem( key
);
2262 data
= JSON
.stringify( mw
.loader
.store
);
2263 localStorage
.setItem( key
, data
);
2265 mw
.trackError( 'resourceloader.exception', {
2267 source
: 'store-localstorage-update'
2271 hasPendingWrites
= false;
2274 function request() {
2275 // If another mw.loader.store.set()/update() call happens in the narrow
2276 // time window between requestIdleCallback() and flushWrites firing, ignore it.
2277 // It'll be saved by the already-scheduled flush.
2278 if ( !hasPendingWrites
) {
2279 hasPendingWrites
= true;
2280 mw
.requestIdleCallback( flushWrites
);
2284 return function () {
2285 // Cancel the previous timer (if it hasn't fired yet)
2286 clearTimeout( timer
);
2287 timer
= setTimeout( request
, 2000 );
2294 // Skeleton user object, extended by the 'mediawiki.user' module.
2301 * @property {mw.Map}
2305 * @property {mw.Map}
2310 // OOUI widgets specific to MediaWiki
2315 // Attach to window and globally alias
2316 window
.mw
= window
.mediaWiki
= mw
;