2 * Base library for MediaWiki.
5 * @alternateClassName mediaWiki
9 var mw
= ( function ( $, undefined ) {
14 var hasOwn
= Object
.prototype.hasOwnProperty
,
15 slice
= Array
.prototype.slice
,
16 trackCallbacks
= $.Callbacks( 'memory' ),
20 * Log a message to window.console, if possible. Useful to force logging of some
21 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
22 * Gets console references in each invocation, so that delayed debugging tools work
23 * fine. No need for optimization here, which would only result in losing logs.
27 * @param {string} msg text for the log entry.
30 function log( msg
, e
) {
31 var console
= window
.console
;
32 if ( console
&& console
.log
) {
34 // If we have an exception object, log it through .error() to trigger
35 // proper stacktraces in browsers that support it. There are no (known)
36 // browsers that don't support .error(), that do support .log() and
37 // have useful exception handling through .log().
38 if ( e
&& console
.error
) {
39 console
.error( String( e
), e
);
44 /* Object constructors */
47 * Creates an object that can be read from or written to from prototype functions
48 * that allow both single and multiple variables at once.
52 * var addies, wanted, results;
54 * // Create your address book
55 * addies = new mw.Map();
57 * // This data could be coming from an external source (eg. API/AJAX)
59 * 'John Doe' : '10 Wall Street, New York, USA',
60 * 'Jane Jackson' : '21 Oxford St, London, UK',
61 * 'Dominique van Halen' : 'Kalverstraat 7, Amsterdam, NL'
64 * wanted = ['Dominique van Halen', 'George Johnson', 'Jane Jackson'];
66 * // You can detect missing keys first
67 * if ( !addies.exists( wanted ) ) {
68 * // One or more are missing (in this case: "George Johnson")
69 * mw.log( 'One or more names were not found in your address book' );
72 * // Or just let it give you what it can
73 * results = addies.get( wanted, 'Middle of Nowhere, Alaska, US' );
74 * mw.log( results['Jane Jackson'] ); // "21 Oxford St, London, UK"
75 * mw.log( results['George Johnson'] ); // "Middle of Nowhere, Alaska, US"
80 * @param {Object|boolean} [values] Value-bearing object to map, or boolean
81 * true to map over the global object. Defaults to an empty object.
83 function Map( values
) {
84 this.values
= values
=== true ? window
: ( values
|| {} );
90 * Get the value of one or multiple a keys.
92 * If called with no arguments, all values will be returned.
94 * @param {string|Array} selection String key or array of keys to get values for.
95 * @param {Mixed} [fallback] Value to use in case key(s) do not exist.
96 * @return mixed If selection was a string returns the value or null,
97 * If selection was an array, returns an object of key/values (value is null if not found),
98 * If selection was not passed or invalid, will return the 'values' object member (be careful as
99 * objects are always passed by reference in JavaScript!).
100 * @return {string|Object|null} Values as a string or object, null if invalid/inexistant.
102 get: function ( selection
, fallback
) {
104 // If we only do this in the `return` block, it'll fail for the
105 // call to get() from the mutli-selection block.
106 fallback
= arguments
.length
> 1 ? fallback
: null;
108 if ( $.isArray( selection
) ) {
109 selection
= slice
.call( selection
);
111 for ( i
= 0; i
< selection
.length
; i
++ ) {
112 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
117 if ( typeof selection
=== 'string' ) {
118 if ( !hasOwn
.call( this.values
, selection
) ) {
121 return this.values
[selection
];
124 if ( selection
=== undefined ) {
128 // invalid selection key
133 * Sets one or multiple key/value pairs.
135 * @param {string|Object} selection String key to set value for, or object mapping keys to values.
136 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
137 * @return {Boolean} This returns true on success, false on failure.
139 set: function ( selection
, value
) {
142 if ( $.isPlainObject( selection
) ) {
143 for ( s
in selection
) {
144 this.values
[s
] = selection
[s
];
148 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
149 this.values
[selection
] = value
;
156 * Checks if one or multiple keys exist.
158 * @param {Mixed} selection String key or array of keys to check
159 * @return {boolean} Existence of key(s)
161 exists: function ( selection
) {
164 if ( $.isArray( selection
) ) {
165 for ( s
= 0; s
< selection
.length
; s
++ ) {
166 if ( typeof selection
[s
] !== 'string' || !hasOwn
.call( this.values
, selection
[s
] ) ) {
172 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
177 * Object constructor for messages.
179 * Similar to the Message class in MediaWiki PHP.
181 * Format defaults to 'text'.
186 * @param {mw.Map} map Message storage
187 * @param {string} key
188 * @param {Array} [parameters]
190 function Message( map
, key
, parameters
) {
191 this.format
= 'text';
194 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
198 Message
.prototype = {
200 * Simple message parser, does $N replacement and nothing else.
202 * This may be overridden to provide a more complex message parser.
204 * The primary override is in mediawiki.jqueryMsg.
206 * This function will not be called for nonexistent messages.
208 parser: function () {
209 var parameters
= this.parameters
;
210 return this.map
.get( this.key
).replace( /\$(\d+)/g, function ( str
, match
) {
211 var index
= parseInt( match
, 10 ) - 1;
212 return parameters
[index
] !== undefined ? parameters
[index
] : '$' + match
;
217 * Appends (does not replace) parameters for replacement to the .parameters property.
219 * @param {Array} parameters
222 params: function ( parameters
) {
224 for ( i
= 0; i
< parameters
.length
; i
+= 1 ) {
225 this.parameters
.push( parameters
[i
] );
231 * Converts message object to its string form based on the state of format.
233 * @return {string} Message as a string in the current form or `<key>` if key does not exist.
235 toString: function () {
238 if ( !this.exists() ) {
239 // Use <key> as text if key does not exist
240 if ( this.format
=== 'escaped' || this.format
=== 'parse' ) {
241 // format 'escaped' and 'parse' need to have the brackets and key html escaped
242 return mw
.html
.escape( '<' + this.key
+ '>' );
244 return '<' + this.key
+ '>';
247 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
248 text
= this.parser();
251 if ( this.format
=== 'escaped' ) {
252 text
= this.parser();
253 text
= mw
.html
.escape( text
);
260 * Changes format to 'parse' and converts message to string
262 * If jqueryMsg is loaded, this parses the message text from wikitext
263 * (where supported) to HTML
265 * Otherwise, it is equivalent to plain.
267 * @return {string} String form of parsed message
270 this.format
= 'parse';
271 return this.toString();
275 * Changes format to 'plain' and converts message to string
277 * This substitutes parameters, but otherwise does not change the
280 * @return {string} String form of plain message
283 this.format
= 'plain';
284 return this.toString();
288 * Changes format to 'text' and converts message to string
290 * If jqueryMsg is loaded, {{-transformation is done where supported
291 * (such as {{plural:}}, {{gender:}}, {{int:}}).
293 * Otherwise, it is equivalent to plain.
296 this.format
= 'text';
297 return this.toString();
301 * Changes the format to 'escaped' and converts message to string
303 * This is equivalent to using the 'text' format (see text method), then
304 * HTML-escaping the output.
306 * @return {string} String form of html escaped message
308 escaped: function () {
309 this.format
= 'escaped';
310 return this.toString();
314 * Checks if message exists
319 exists: function () {
320 return this.map
.exists( this.key
);
331 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
333 * On browsers that implement the Navigation Timing API, this function will produce floating-point
334 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
335 * it will fall back to using `Date`.
337 * @returns {number} Current time
340 var perf
= window
.performance
,
341 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
342 return navStart
&& typeof perf
.now
=== 'function' ?
343 function () { return navStart
+ perf
.now(); } :
344 function () { return +new Date(); };
348 * Track an analytic event.
350 * This method provides a generic means for MediaWiki JavaScript code to capture state
351 * information for analysis. Each logged event specifies a string topic name that describes
352 * the kind of event that it is. Topic names consist of dot-separated path components,
353 * arranged from most general to most specific. Each path component should have a clear and
354 * well-defined purpose.
356 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
357 * events that match their subcription, including those that fired before the handler was
360 * @param {string} topic Topic name
361 * @param {Object} [data] Data describing the event, encoded as an object
363 track: function ( topic
, data
) {
364 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
365 trackCallbacks
.fire( trackQueue
);
369 * Register a handler for subset of analytic events, specified by topic
371 * Handlers will be called once for each tracked event, including any events that fired before the
372 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
373 * the exact time at which the event fired, a string 'topic' property naming the event, and a
374 * 'data' property which is an object of event-specific data. The event topic and event data are
375 * also passed to the callback as the first and second arguments, respectively.
377 * @param {string} topic Handle events whose name starts with this string prefix
378 * @param {Function} callback Handler to call for each matching tracked event
380 trackSubscribe: function ( topic
, callback
) {
383 trackCallbacks
.add( function ( trackQueue
) {
385 for ( ; seen
< trackQueue
.length
; seen
++ ) {
386 event
= trackQueue
[ seen
];
387 if ( event
.topic
.indexOf( topic
) === 0 ) {
388 callback
.call( event
, event
.topic
, event
.data
);
395 * Dummy placeholder for {@link mw.log}
399 var log = function () {};
400 log
.warn = function () {};
401 log
.deprecate = function ( obj
, key
, val
) {
407 // Make the Map constructor publicly available.
410 // Make the Message constructor publicly available.
414 * Map of configuration values
416 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
419 * If `$wgLegacyJavaScriptGlobals` is true, this Map will put its values in the
420 * global window object.
422 * @property {mw.Map} config
424 // Dummy placeholder. Re-assigned in ResourceLoaderStartupModule with an instance of `mw.Map`.
428 * Empty object that plugins can be installed in.
434 * Access container for deprecated functionality that can be moved from
435 * from their legacy location and attached to this object (e.g. a global
436 * function that is deprecated and as stop-gap can be exposed through here).
438 * This was reserved for future use but never ended up being used.
440 * @deprecated since 1.22: Let deprecated identifiers keep their original name
441 * and use mw.log#deprecate to create an access container for tracking.
447 * Localization system
455 * Get a message object.
457 * Similar to wfMessage() in MediaWiki PHP.
459 * @param {string} key Key of message to get
460 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
461 * @return {mw.Message}
463 message: function ( key
) {
464 // Variadic arguments
465 var parameters
= slice
.call( arguments
, 1 );
466 return new Message( mw
.messages
, key
, parameters
);
470 * Get a message string using 'text' format.
472 * Similar to wfMsg() in MediaWiki PHP.
475 * @param {string} key Key of message to get
476 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
480 return mw
.message
.apply( mw
.message
, arguments
).toString();
484 * Client-side module loader which integrates with the MediaWiki ResourceLoader
488 loader
: ( function () {
490 /* Private Members */
493 * Mapping of registered modules
495 * The jquery module is pre-registered, because it must have already
496 * been provided for this object to have been built, and in debug mode
497 * jquery would have been provided through a unique loader request,
498 * making it impossible to hold back registration of jquery until after
501 * For exact details on support for script, style and messages, look at
502 * mw.loader.implement.
507 * 'version': ############## (unix timestamp),
508 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
509 * 'group': 'somegroup', (or) null,
510 * 'source': 'local', 'someforeignwiki', (or) null
511 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error' or 'missing'
514 * 'messages': { 'key': 'value' },
523 // Mapping of sources, keyed by source-id, values are objects.
527 // 'loadScript': 'http://foo.bar/w/load.php'
532 // List of modules which will be loaded as when ready
534 // List of modules to be loaded
536 // List of callback functions waiting for modules to be ready to be called
538 // Selector cache for the marker element. Use getMarker() to get/use the marker!
540 // Buffer for addEmbeddedCSS.
542 // Callbacks for addEmbeddedCSS.
543 cssCallbacks
= $.Callbacks();
545 /* Private methods */
547 function getMarker() {
553 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
554 if ( $marker
.length
) {
557 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
558 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
564 * Create a new style tag and add it to the DOM.
567 * @param {string} text CSS text
568 * @param {HTMLElement|jQuery} [nextnode=document.head] The element where the style tag should be
569 * inserted before. Otherwise it will be appended to `<head>`.
570 * @return {HTMLElement} Reference to the created `<style>` element.
572 function newStyleTag( text
, nextnode
) {
573 var s
= document
.createElement( 'style' );
574 // Insert into document before setting cssText (bug 33305)
576 // Must be inserted with native insertBefore, not $.fn.before.
577 // When using jQuery to insert it, like $nextnode.before( s ),
578 // then IE6 will throw "Access is denied" when trying to append
579 // to .cssText later. Some kind of weird security measure.
580 // http://stackoverflow.com/q/12586482/319266
581 // Works: jsfiddle.net/zJzMy/1
582 // Fails: jsfiddle.net/uJTQz
583 // Works again: http://jsfiddle.net/Azr4w/ (diff: the next 3 lines)
584 if ( nextnode
.jquery
) {
585 nextnode
= nextnode
.get( 0 );
587 nextnode
.parentNode
.insertBefore( s
, nextnode
);
589 document
.getElementsByTagName( 'head' )[0].appendChild( s
);
591 if ( s
.styleSheet
) {
593 s
.styleSheet
.cssText
= text
;
596 // (Safari sometimes borks on non-string values,
597 // play safe by casting to a string, just in case.)
598 s
.appendChild( document
.createTextNode( String( text
) ) );
604 * Checks whether it is safe to add this css to a stylesheet.
607 * @param {string} cssText
608 * @return {boolean} False if a new one must be created.
610 function canExpandStylesheetWith( cssText
) {
611 // Makes sure that cssText containing `@import`
612 // rules will end up in a new stylesheet (as those only work when
613 // placed at the start of a stylesheet; bug 35562).
614 return cssText
.indexOf( '@import' ) === -1;
618 * Add a bit of CSS text to the current browser page.
620 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
621 * or create a new one based on whether the given `cssText` is safe for extension.
623 * @param {string} [cssText=cssBuffer] If called without cssText,
624 * the internal buffer will be inserted instead.
625 * @param {Function} [callback]
627 function addEmbeddedCSS( cssText
, callback
) {
631 cssCallbacks
.add( callback
);
634 // Yield once before inserting the <style> tag. There are likely
635 // more calls coming up which we can combine this way.
636 // Appending a stylesheet and waiting for the browser to repaint
637 // is fairly expensive, this reduces it (bug 45810)
639 // Be careful not to extend the buffer with css that needs a new stylesheet
640 if ( !cssBuffer
|| canExpandStylesheetWith( cssText
) ) {
641 // Linebreak for somewhat distinguishable sections
642 // (the rl-cachekey comment separating each)
643 cssBuffer
+= '\n' + cssText
;
644 // TODO: Use requestAnimationFrame in the future which will
645 // perform even better by not injecting styles while the browser
647 setTimeout( function () {
648 // Can't pass addEmbeddedCSS to setTimeout directly because Firefox
649 // (below version 13) has the non-standard behaviour of passing a
650 // numerical "lateness" value as first argument to this callback
651 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
657 // This is a delayed call and we got a buffer still
658 } else if ( cssBuffer
) {
662 // This is a delayed call, but buffer is already cleared by
663 // another delayed call.
667 // By default, always create a new <style>. Appending text
668 // to a <style> tag means the contents have to be re-parsed (bug 45810).
669 // Except, of course, in IE below 9, in there we default to
670 // re-using and appending to a <style> tag due to the
671 // IE stylesheet limit (bug 31676).
672 if ( 'documentMode' in document
&& document
.documentMode
<= 9 ) {
674 $style
= getMarker().prev();
675 // Verify that the the element before Marker actually is a
676 // <style> tag and one that came from ResourceLoader
677 // (not some other style tag or even a `<meta>` or `<script>`).
678 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
679 // There's already a dynamic <style> tag present and
680 // canExpandStylesheetWith() gave a green light to append more to it.
681 styleEl
= $style
.get( 0 );
682 if ( styleEl
.styleSheet
) {
684 styleEl
.styleSheet
.cssText
+= cssText
; // IE
686 log( 'addEmbeddedCSS fail', e
);
689 styleEl
.appendChild( document
.createTextNode( String( cssText
) ) );
691 cssCallbacks
.fire().empty();
696 $( newStyleTag( cssText
, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
698 cssCallbacks
.fire().empty();
702 * Generates an ISO8601 "basic" string from a UNIX timestamp
705 function formatVersionNumber( timestamp
) {
707 function pad( a
, b
, c
) {
708 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
710 d
.setTime( timestamp
* 1000 );
712 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
713 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
718 * Resolves dependencies and detects circular references.
721 * @param {string} module Name of the top-level module whose dependencies shall be
722 * resolved and sorted.
723 * @param {Array} resolved Returns a topological sort of the given module and its
724 * dependencies, such that later modules depend on earlier modules. The array
725 * contains the module names. If the array contains already some module names,
726 * this function appends its result to the pre-existing array.
727 * @param {Object} [unresolved] Hash used to track the current dependency
728 * chain; used to report loops in the dependency graph.
729 * @throws {Error} If any unregistered module or a dependency loop is encountered
731 function sortDependencies( module
, resolved
, unresolved
) {
734 if ( registry
[module
] === undefined ) {
735 throw new Error( 'Unknown dependency: ' + module
);
737 // Resolves dynamic loader function and replaces it with its own results
738 if ( $.isFunction( registry
[module
].dependencies
) ) {
739 registry
[module
].dependencies
= registry
[module
].dependencies();
740 // Ensures the module's dependencies are always in an array
741 if ( typeof registry
[module
].dependencies
!== 'object' ) {
742 registry
[module
].dependencies
= [registry
[module
].dependencies
];
745 if ( $.inArray( module
, resolved
) !== -1 ) {
746 // Module already resolved; nothing to do.
749 // unresolved is optional, supply it if not passed in
753 // Tracks down dependencies
754 deps
= registry
[module
].dependencies
;
756 for ( n
= 0; n
< len
; n
+= 1 ) {
757 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
758 if ( unresolved
[deps
[n
]] ) {
760 'Circular reference detected: ' + module
+
766 unresolved
[module
] = true;
767 sortDependencies( deps
[n
], resolved
, unresolved
);
768 delete unresolved
[module
];
771 resolved
[resolved
.length
] = module
;
775 * Gets a list of module names that a module depends on in their proper dependency
779 * @param {string} module Module name or array of string module names
780 * @return {Array} list of dependencies, including 'module'.
781 * @throws {Error} If circular reference is detected
783 function resolve( module
) {
786 // Allow calling with an array of module names
787 if ( $.isArray( module
) ) {
789 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
790 sortDependencies( module
[m
], resolved
);
795 if ( typeof module
=== 'string' ) {
797 sortDependencies( module
, resolved
);
801 throw new Error( 'Invalid module argument: ' + module
);
805 * Narrows a list of module names down to those matching a specific
806 * state (see comment on top of this scope for a list of valid states).
807 * One can also filter for 'unregistered', which will return the
808 * modules names that don't have a registry entry.
811 * @param {string|string[]} states Module states to filter by
812 * @param {Array} [modules] List of module names to filter (optional, by default the entire
814 * @return {Array} List of filtered module names
816 function filter( states
, modules
) {
817 var list
, module
, s
, m
;
819 // Allow states to be given as a string
820 if ( typeof states
=== 'string' ) {
823 // If called without a list of modules, build and use a list of all modules
825 if ( modules
=== undefined ) {
827 for ( module
in registry
) {
828 modules
[modules
.length
] = module
;
831 // Build a list of modules which are in one of the specified states
832 for ( s
= 0; s
< states
.length
; s
+= 1 ) {
833 for ( m
= 0; m
< modules
.length
; m
+= 1 ) {
834 if ( registry
[modules
[m
]] === undefined ) {
835 // Module does not exist
836 if ( states
[s
] === 'unregistered' ) {
838 list
[list
.length
] = modules
[m
];
841 // Module exists, check state
842 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
844 list
[list
.length
] = modules
[m
];
853 * Determine whether all dependencies are in state 'ready', which means we may
854 * execute the module or job now.
857 * @param {Array} dependencies Dependencies (module names) to be checked.
858 * @return {boolean} True if all dependencies are in state 'ready', false otherwise
860 function allReady( dependencies
) {
861 return filter( 'ready', dependencies
).length
=== dependencies
.length
;
865 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
866 * and modules that depend upon this module. if the given module failed, propagate the 'error'
867 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
868 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
871 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
873 function handlePending( module
) {
874 var j
, job
, hasErrors
, m
, stateChange
;
877 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) !== -1 ) {
878 // If the current module failed, mark all dependent modules also as failed.
879 // Iterate until steady-state to propagate the error state upwards in the
883 for ( m
in registry
) {
884 if ( $.inArray( registry
[m
].state
, ['error', 'missing'] ) === -1 ) {
885 if ( filter( ['error', 'missing'], registry
[m
].dependencies
).length
> 0 ) {
886 registry
[m
].state
= 'error';
891 } while ( stateChange
);
894 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
895 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
896 hasErrors
= filter( ['error', 'missing'], jobs
[j
].dependencies
).length
> 0;
897 if ( hasErrors
|| allReady( jobs
[j
].dependencies
) ) {
898 // All dependencies satisfied, or some have errors
904 if ( $.isFunction( job
.error
) ) {
905 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [module
] );
908 if ( $.isFunction( job
.ready
) ) {
913 // A user-defined callback raised an exception.
914 // Swallow it to protect our state machine!
915 log( 'Exception thrown by job.error', e
);
920 if ( registry
[module
].state
=== 'ready' ) {
921 // The current module became 'ready'. Set it in the module store, and recursively execute all
922 // dependent modules that are loaded and now have all dependencies satisfied.
923 mw
.loader
.store
.set( module
, registry
[module
] );
924 for ( m
in registry
) {
925 if ( registry
[m
].state
=== 'loaded' && allReady( registry
[m
].dependencies
) ) {
933 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
934 * depending on whether document-ready has occurred yet and whether we are in async mode.
937 * @param {string} src URL to script, will be used as the src attribute in the script tag
938 * @param {Function} [callback] Callback which will be run when the script is done
940 function addScript( src
, callback
, async
) {
941 /*jshint evil:true */
942 var script
, head
, done
;
944 // Using isReady directly instead of storing it locally from
945 // a $.fn.ready callback (bug 31895).
946 if ( $.isReady
|| async
) {
947 // Can't use jQuery.getScript because that only uses <script> for cross-domain,
948 // it uses XHR and eval for same-domain scripts, which we don't want because it
949 // messes up line numbers.
950 // The below is based on jQuery ([jquery@1.8.2]/src/ajax/script.js)
952 // IE-safe way of getting the <head>. document.head isn't supported
953 // in old IE, and doesn't work when in the <head>.
955 head
= document
.getElementsByTagName( 'head' )[0] || document
.body
;
957 script
= document
.createElement( 'script' );
960 if ( $.isFunction( callback
) ) {
961 script
.onload
= script
.onreadystatechange = function () {
966 || /loaded|complete/.test( script
.readyState
)
971 // Handle memory leak in IE
972 script
.onload
= script
.onreadystatechange
= null;
974 // Detach the element from the document
975 if ( script
.parentNode
) {
976 script
.parentNode
.removeChild( script
);
979 // Dereference the element from javascript
987 if ( window
.opera
) {
988 // Appending to the <head> blocks rendering completely in Opera,
989 // so append to the <body> after document ready. This means the
990 // scripts only start loading after the document has been rendered,
991 // but so be it. Opera users don't deserve faster web pages if their
992 // browser makes it impossible.
994 document
.body
.appendChild( script
);
997 head
.appendChild( script
);
1000 document
.write( mw
.html
.element( 'script', { 'src': src
}, '' ) );
1001 if ( $.isFunction( callback
) ) {
1002 // Document.write is synchronous, so this is called when it's done
1003 // FIXME: that's a lie. doc.write isn't actually synchronous
1010 * Executes a loaded module, making it ready to use
1013 * @param {string} module Module name to execute
1015 function execute( module
) {
1016 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
,
1017 cssHandlesRegistered
= false;
1019 if ( registry
[module
] === undefined ) {
1020 throw new Error( 'Module has not been registered yet: ' + module
);
1021 } else if ( registry
[module
].state
=== 'registered' ) {
1022 throw new Error( 'Module has not been requested from the server yet: ' + module
);
1023 } else if ( registry
[module
].state
=== 'loading' ) {
1024 throw new Error( 'Module has not completed loading yet: ' + module
);
1025 } else if ( registry
[module
].state
=== 'ready' ) {
1026 throw new Error( 'Module has already been executed: ' + module
);
1030 * Define loop-function here for efficiency
1031 * and to avoid re-using badly scoped variables.
1034 function addLink( media
, url
) {
1035 var el
= document
.createElement( 'link' );
1036 getMarker().before( el
); // IE: Insert in dom before setting href
1037 el
.rel
= 'stylesheet';
1038 if ( media
&& media
!== 'all' ) {
1044 function runScript() {
1045 var script
, markModuleReady
, nestedAddScript
;
1047 script
= registry
[module
].script
;
1048 markModuleReady = function () {
1049 registry
[module
].state
= 'ready';
1050 handlePending( module
);
1052 nestedAddScript = function ( arr
, callback
, async
, i
) {
1053 // Recursively call addScript() in its own callback
1054 // for each element of arr.
1055 if ( i
>= arr
.length
) {
1056 // We're at the end of the array
1061 addScript( arr
[i
], function () {
1062 nestedAddScript( arr
, callback
, async
, i
+ 1 );
1066 if ( $.isArray( script
) ) {
1067 nestedAddScript( script
, markModuleReady
, registry
[module
].async
, 0 );
1068 } else if ( $.isFunction( script
) ) {
1069 registry
[module
].state
= 'ready';
1071 handlePending( module
);
1074 // This needs to NOT use mw.log because these errors are common in production mode
1075 // and not in debug mode, such as when a symbol that should be global isn't exported
1076 log( 'Exception thrown by ' + module
, e
);
1077 registry
[module
].state
= 'error';
1078 handlePending( module
);
1082 // This used to be inside runScript, but since that is now fired asychronously
1083 // (after CSS is loaded) we need to set it here right away. It is crucial that
1084 // when execute() is called this is set synchronously, otherwise modules will get
1085 // executed multiple times as the registry will state that it isn't loading yet.
1086 registry
[module
].state
= 'loading';
1088 // Add localizations to message system
1089 if ( $.isPlainObject( registry
[module
].messages
) ) {
1090 mw
.messages
.set( registry
[module
].messages
);
1093 if ( $.isReady
|| registry
[module
].async
) {
1094 // Make sure we don't run the scripts until all (potentially asynchronous)
1095 // stylesheet insertions have completed.
1098 checkCssHandles = function () {
1099 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1100 // one of the cssHandles is fired while we're still creating more handles.
1101 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1103 runScript
= undefined; // Revoke
1106 cssHandle = function () {
1107 var check
= checkCssHandles
;
1109 return function () {
1113 check
= undefined; // Revoke
1119 // We are in blocking mode, and so we can't afford to wait for CSS
1120 cssHandle = function () {};
1122 checkCssHandles
= runScript
;
1125 // Process styles (see also mw.loader.implement)
1126 // * back-compat: { <media>: css }
1127 // * back-compat: { <media>: [url, ..] }
1128 // * { "css": [css, ..] }
1129 // * { "url": { <media>: [url, ..] } }
1130 if ( $.isPlainObject( registry
[module
].style
) ) {
1131 for ( key
in registry
[module
].style
) {
1132 value
= registry
[module
].style
[key
];
1135 if ( key
!== 'url' && key
!== 'css' ) {
1136 // Backwards compatibility, key is a media-type
1137 if ( typeof value
=== 'string' ) {
1138 // back-compat: { <media>: css }
1139 // Ignore 'media' because it isn't supported (nor was it used).
1140 // Strings are pre-wrapped in "@media". The media-type was just ""
1141 // (because it had to be set to something).
1142 // This is one of the reasons why this format is no longer used.
1143 addEmbeddedCSS( value
, cssHandle() );
1145 // back-compat: { <media>: [url, ..] }
1151 // Array of css strings in key 'css',
1152 // or back-compat array of urls from media-type
1153 if ( $.isArray( value
) ) {
1154 for ( i
= 0; i
< value
.length
; i
+= 1 ) {
1155 if ( key
=== 'bc-url' ) {
1156 // back-compat: { <media>: [url, ..] }
1157 addLink( media
, value
[i
] );
1158 } else if ( key
=== 'css' ) {
1159 // { "css": [css, ..] }
1160 addEmbeddedCSS( value
[i
], cssHandle() );
1163 // Not an array, but a regular object
1164 // Array of urls inside media-type key
1165 } else if ( typeof value
=== 'object' ) {
1166 // { "url": { <media>: [url, ..] } }
1167 for ( media
in value
) {
1168 urls
= value
[media
];
1169 for ( i
= 0; i
< urls
.length
; i
+= 1 ) {
1170 addLink( media
, urls
[i
] );
1178 cssHandlesRegistered
= true;
1183 * Adds a dependencies to the queue with optional callbacks to be run
1184 * when the dependencies are ready or fail
1187 * @param {string|string[]} dependencies Module name or array of string module names
1188 * @param {Function} [ready] Callback to execute when all dependencies are ready
1189 * @param {Function} [error] Callback to execute when any dependency fails
1190 * @param {boolean} [async] If true, load modules asynchronously even if
1191 * document ready has not yet occurred.
1193 function request( dependencies
, ready
, error
, async
) {
1196 // Allow calling by single module name
1197 if ( typeof dependencies
=== 'string' ) {
1198 dependencies
= [dependencies
];
1201 // Add ready and error callbacks if they were given
1202 if ( ready
!== undefined || error
!== undefined ) {
1203 jobs
[jobs
.length
] = {
1204 'dependencies': filter(
1205 ['registered', 'loading', 'loaded'],
1213 // Queue up any dependencies that are registered
1214 dependencies
= filter( ['registered'], dependencies
);
1215 for ( n
= 0; n
< dependencies
.length
; n
+= 1 ) {
1216 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
1217 queue
[queue
.length
] = dependencies
[n
];
1219 // Mark this module as async in the registry
1220 registry
[dependencies
[n
]].async
= true;
1229 function sortQuery(o
) {
1230 var sorted
= {}, key
, a
= [];
1232 if ( hasOwn
.call( o
, key
) ) {
1237 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
1238 sorted
[a
[key
]] = o
[a
[key
]];
1244 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1245 * to a query string of the form foo.bar,baz|bar.baz,quux
1248 function buildModulesString( moduleMap
) {
1249 var arr
= [], p
, prefix
;
1250 for ( prefix
in moduleMap
) {
1251 p
= prefix
=== '' ? '' : prefix
+ '.';
1252 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
1254 return arr
.join( '|' );
1258 * Asynchronously append a script tag to the end of the body
1259 * that invokes load.php
1261 * @param {Object} moduleMap Module map, see #buildModulesString
1262 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1263 * @param {string} sourceLoadScript URL of load.php
1264 * @param {boolean} async If true, use an asynchronous request even if document ready has not yet occurred
1266 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
) {
1267 var request
= $.extend(
1268 { modules
: buildModulesString( moduleMap
) },
1271 request
= sortQuery( request
);
1272 // Asynchronously append a script tag to the end of the body
1273 // Append &* to avoid triggering the IE6 extension check
1274 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*', null, async
);
1277 /* Public Members */
1280 * The module registry is exposed as an aid for debugging and inspecting page
1281 * state; it is not a public interface for modifying the registry.
1287 moduleRegistry
: registry
,
1290 * @inheritdoc #newStyleTag
1293 addStyleTag
: newStyleTag
,
1296 * Batch-request queued dependencies from the server.
1299 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
1300 source
, concatSource
, group
, g
, i
, modules
, maxVersion
, sourceLoadScript
,
1301 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1302 lastDotIndex
, prefix
, suffix
, bytesAdded
, async
;
1304 // Build a list of request parameters common to all requests.
1306 skin
: mw
.config
.get( 'skin' ),
1307 lang
: mw
.config
.get( 'wgUserLanguage' ),
1308 debug
: mw
.config
.get( 'debug' )
1310 // Split module batch by source and by group.
1312 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
1314 // Appends a list of modules from the queue to the batch
1315 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
1316 // Only request modules which are registered
1317 if ( registry
[queue
[q
]] !== undefined && registry
[queue
[q
]].state
=== 'registered' ) {
1318 // Prevent duplicate entries
1319 if ( $.inArray( queue
[q
], batch
) === -1 ) {
1320 batch
[batch
.length
] = queue
[q
];
1321 // Mark registered modules as loading
1322 registry
[queue
[q
]].state
= 'loading';
1327 mw
.loader
.store
.init();
1328 if ( mw
.loader
.store
.enabled
) {
1330 batch
= $.grep( batch
, function ( module
) {
1331 var source
= mw
.loader
.store
.get( module
);
1333 concatSource
.push( source
);
1338 $.globalEval( concatSource
.join( ';' ) );
1341 // Early exit if there's nothing to load...
1342 if ( !batch
.length
) {
1346 // The queue has been processed into the batch, clear up the queue.
1349 // Always order modules alphabetically to help reduce cache
1350 // misses for otherwise identical content.
1353 // Split batch by source and by group.
1354 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
1355 bSource
= registry
[batch
[b
]].source
;
1356 bGroup
= registry
[batch
[b
]].group
;
1357 if ( splits
[bSource
] === undefined ) {
1358 splits
[bSource
] = {};
1360 if ( splits
[bSource
][bGroup
] === undefined ) {
1361 splits
[bSource
][bGroup
] = [];
1363 bSourceGroup
= splits
[bSource
][bGroup
];
1364 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
1367 // Clear the batch - this MUST happen before we append any
1368 // script elements to the body or it's possible that a script
1369 // will be locally cached, instantly load, and work the batch
1370 // again, all before we've cleared it causing each request to
1371 // include modules which are already loaded.
1374 for ( source
in splits
) {
1376 sourceLoadScript
= sources
[source
].loadScript
;
1378 for ( group
in splits
[source
] ) {
1380 // Cache access to currently selected list of
1381 // modules for this group from this source.
1382 modules
= splits
[source
][group
];
1384 // Calculate the highest timestamp
1386 for ( g
= 0; g
< modules
.length
; g
+= 1 ) {
1387 if ( registry
[modules
[g
]].version
> maxVersion
) {
1388 maxVersion
= registry
[modules
[g
]].version
;
1392 currReqBase
= $.extend( { version
: formatVersionNumber( maxVersion
) }, reqBase
);
1393 // For user modules append a user name to the request.
1394 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1395 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1397 currReqBaseLength
= $.param( currReqBase
).length
;
1399 // We may need to split up the request to honor the query string length limit,
1400 // so build it piece by piece.
1401 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1403 moduleMap
= {}; // { prefix: [ suffixes ] }
1405 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
1406 // Determine how many bytes this module would add to the query string
1407 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
1408 // Note that these substr() calls work even if lastDotIndex == -1
1409 prefix
= modules
[i
].substr( 0, lastDotIndex
);
1410 suffix
= modules
[i
].substr( lastDotIndex
+ 1 );
1411 bytesAdded
= moduleMap
[prefix
] !== undefined
1412 ? suffix
.length
+ 3 // '%2C'.length == 3
1413 : modules
[i
].length
+ 3; // '%7C'.length == 3
1415 // If the request would become too long, create a new one,
1416 // but don't create empty requests
1417 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1418 // This request would become too long, create a new one
1419 // and fire off the old one
1420 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1423 l
= currReqBaseLength
+ 9;
1425 if ( moduleMap
[prefix
] === undefined ) {
1426 moduleMap
[prefix
] = [];
1428 moduleMap
[prefix
].push( suffix
);
1429 if ( !registry
[modules
[i
]].async
) {
1430 // If this module is blocking, make the entire request blocking
1431 // This is slightly suboptimal, but in practice mixing of blocking
1432 // and async modules will only occur in debug mode.
1437 // If there's anything left in moduleMap, request that too
1438 if ( !$.isEmptyObject( moduleMap
) ) {
1439 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1446 * Register a source.
1448 * @param {string} id Short lowercase a-Z string representing a source, only used internally.
1449 * @param {Object} props Object containing only the loadScript property which is a url to
1450 * the load.php location of the source.
1453 addSource: function ( id
, props
) {
1455 // Allow multiple additions
1456 if ( typeof id
=== 'object' ) {
1457 for ( source
in id
) {
1458 mw
.loader
.addSource( source
, id
[source
] );
1463 if ( sources
[id
] !== undefined ) {
1464 throw new Error( 'source already registered: ' + id
);
1467 sources
[id
] = props
;
1473 * Register a module, letting the system know about it and its
1474 * properties. Startup modules contain calls to this function.
1476 * @param {string} module Module name
1477 * @param {number} version Module version number as a timestamp (falls backs to 0)
1478 * @param {string|Array|Function} dependencies One string or array of strings of module
1479 * names on which this module depends, or a function that returns that array.
1480 * @param {string} [group=null] Group which the module is in
1481 * @param {string} [source='local'] Name of the source
1483 register: function ( module
, version
, dependencies
, group
, source
) {
1485 // Allow multiple registration
1486 if ( typeof module
=== 'object' ) {
1487 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
1488 // module is an array of module names
1489 if ( typeof module
[m
] === 'string' ) {
1490 mw
.loader
.register( module
[m
] );
1491 // module is an array of arrays
1492 } else if ( typeof module
[m
] === 'object' ) {
1493 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
1499 if ( typeof module
!== 'string' ) {
1500 throw new Error( 'module must be a string, not a ' + typeof module
);
1502 if ( registry
[module
] !== undefined ) {
1503 throw new Error( 'module already registered: ' + module
);
1505 // List the module as registered
1506 registry
[module
] = {
1507 version
: version
!== undefined ? parseInt( version
, 10 ) : 0,
1509 group
: typeof group
=== 'string' ? group
: null,
1510 source
: typeof source
=== 'string' ? source
: 'local',
1513 if ( typeof dependencies
=== 'string' ) {
1514 // Allow dependencies to be given as a single module name
1515 registry
[module
].dependencies
= [ dependencies
];
1516 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1517 // Allow dependencies to be given as an array of module names
1518 // or a function which returns an array
1519 registry
[module
].dependencies
= dependencies
;
1524 * Implement a module given the components that make up the module.
1526 * When #load or #using requests one or more modules, the server
1527 * response contain calls to this function.
1529 * All arguments are required.
1531 * @param {string} module Name of module
1532 * @param {Function|Array} script Function with module code or Array of URLs to
1533 * be used as the src attribute of a new `<script>` tag.
1534 * @param {Object} style Should follow one of the following patterns:
1536 * { "css": [css, ..] }
1537 * { "url": { <media>: [url, ..] } }
1539 * And for backwards compatibility (needs to be supported forever due to caching):
1542 * { <media>: [url, ..] }
1544 * The reason css strings are not concatenated anymore is bug 31676. We now check
1545 * whether it's safe to extend the stylesheet (see #canExpandStylesheetWith).
1547 * @param {Object} msgs List of key/value pairs to be added to mw#messages.
1549 implement: function ( module
, script
, style
, msgs
) {
1551 if ( typeof module
!== 'string' ) {
1552 throw new Error( 'module must be a string, not a ' + typeof module
);
1554 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
1555 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
1557 if ( !$.isPlainObject( style
) ) {
1558 throw new Error( 'style must be an object, not a ' + typeof style
);
1560 if ( !$.isPlainObject( msgs
) ) {
1561 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
1563 // Automatically register module
1564 if ( registry
[module
] === undefined ) {
1565 mw
.loader
.register( module
);
1567 // Check for duplicate implementation
1568 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
1569 throw new Error( 'module already implemented: ' + module
);
1571 // Attach components
1572 registry
[module
].script
= script
;
1573 registry
[module
].style
= style
;
1574 registry
[module
].messages
= msgs
;
1575 // The module may already have been marked as erroneous
1576 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) === -1 ) {
1577 registry
[module
].state
= 'loaded';
1578 if ( allReady( registry
[module
].dependencies
) ) {
1585 * Execute a function as soon as one or more required modules are ready.
1587 * @param {string|Array} dependencies Module name or array of modules names the callback
1588 * dependends on to be ready before executing
1589 * @param {Function} [ready] callback to execute when all dependencies are ready
1590 * @param {Function} [error] callback to execute when if dependencies have a errors
1592 using: function ( dependencies
, ready
, error
) {
1593 var tod
= typeof dependencies
;
1595 if ( tod
!== 'object' && tod
!== 'string' ) {
1596 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1598 // Allow calling with a single dependency as a string
1599 if ( tod
=== 'string' ) {
1600 dependencies
= [ dependencies
];
1602 // Resolve entire dependency map
1603 dependencies
= resolve( dependencies
);
1604 if ( allReady( dependencies
) ) {
1605 // Run ready immediately
1606 if ( $.isFunction( ready
) ) {
1609 } else if ( filter( ['error', 'missing'], dependencies
).length
) {
1610 // Execute error immediately if any dependencies have errors
1611 if ( $.isFunction( error
) ) {
1612 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1616 // Not all dependencies are ready: queue up a request
1617 request( dependencies
, ready
, error
);
1622 * Load an external script or one or more modules.
1624 * @param {string|Array} modules Either the name of a module, array of modules,
1625 * or a URL of an external script or style
1626 * @param {string} [type='text/javascript'] mime-type to use if calling with a URL of an
1627 * external script or style; acceptable values are "text/css" and
1628 * "text/javascript"; if no type is provided, text/javascript is assumed.
1629 * @param {boolean} [async] If true, load modules asynchronously
1630 * even if document ready has not yet occurred. If false, block before
1631 * document ready and load async after. If not set, true will be
1632 * assumed if loading a URL, and false will be assumed otherwise.
1634 load: function ( modules
, type
, async
) {
1635 var filtered
, m
, module
, l
;
1638 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1639 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1641 // Allow calling with an external url or single dependency as a string
1642 if ( typeof modules
=== 'string' ) {
1643 // Support adding arbitrary external scripts
1644 if ( /^(https?:)?\/\//.test( modules
) ) {
1645 if ( async
=== undefined ) {
1646 // Assume async for bug 34542
1649 if ( type
=== 'text/css' ) {
1650 // IE7-8 throws security warnings when inserting a <link> tag
1651 // with a protocol-relative URL set though attributes (instead of
1652 // properties) - when on HTTPS. See also bug #.
1653 l
= document
.createElement( 'link' );
1654 l
.rel
= 'stylesheet';
1656 $( 'head' ).append( l
);
1659 if ( type
=== 'text/javascript' || type
=== undefined ) {
1660 addScript( modules
, null, async
);
1664 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1666 // Called with single module
1667 modules
= [ modules
];
1670 // Filter out undefined modules, otherwise resolve() will throw
1671 // an exception for trying to load an undefined module.
1672 // Undefined modules are acceptable here in load(), because load() takes
1673 // an array of unrelated modules, whereas the modules passed to
1674 // using() are related and must all be loaded.
1675 for ( filtered
= [], m
= 0; m
< modules
.length
; m
+= 1 ) {
1676 module
= registry
[modules
[m
]];
1677 if ( module
!== undefined ) {
1678 if ( $.inArray( module
.state
, ['error', 'missing'] ) === -1 ) {
1679 filtered
[filtered
.length
] = modules
[m
];
1684 if ( filtered
.length
=== 0 ) {
1687 // Resolve entire dependency map
1688 filtered
= resolve( filtered
);
1689 // If all modules are ready, nothing to be done
1690 if ( allReady( filtered
) ) {
1693 // If any modules have errors: also quit.
1694 if ( filter( ['error', 'missing'], filtered
).length
) {
1697 // Since some modules are not yet ready, queue up a request.
1698 request( filtered
, undefined, undefined, async
);
1702 * Change the state of one or more modules.
1704 * @param {string|Object} module Module name or object of module name/state pairs
1705 * @param {string} state State name
1707 state: function ( module
, state
) {
1710 if ( typeof module
=== 'object' ) {
1711 for ( m
in module
) {
1712 mw
.loader
.state( m
, module
[m
] );
1716 if ( registry
[module
] === undefined ) {
1717 mw
.loader
.register( module
);
1719 if ( $.inArray( state
, ['ready', 'error', 'missing'] ) !== -1
1720 && registry
[module
].state
!== state
) {
1721 // Make sure pending modules depending on this one get executed if their
1722 // dependencies are now fulfilled!
1723 registry
[module
].state
= state
;
1724 handlePending( module
);
1726 registry
[module
].state
= state
;
1731 * Get the version of a module.
1733 * @param {string} module Name of module to get version for
1735 getVersion: function ( module
) {
1736 if ( registry
[module
] !== undefined && registry
[module
].version
!== undefined ) {
1737 return formatVersionNumber( registry
[module
].version
);
1743 * @inheritdoc #getVersion
1744 * @deprecated since 1.18 use #getVersion instead
1746 version: function () {
1747 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1751 * Get the state of a module.
1753 * @param {string} module Name of module to get state for
1755 getState: function ( module
) {
1756 if ( registry
[module
] !== undefined && registry
[module
].state
!== undefined ) {
1757 return registry
[module
].state
;
1763 * Get names of all registered modules.
1767 getModuleNames: function () {
1768 return $.map( registry
, function ( i
, key
) {
1774 * Load the `mediawiki.user` module.
1776 * For backwards-compatibility with cached pages from before 2013 where:
1778 * - the `mediawiki.user` module didn't exist yet
1779 * - `mw.user` was still part of mediawiki.js
1780 * - `mw.loader.go` still existed and called after `mw.loader.load()`
1783 mw
.loader
.load( 'mediawiki.user' );
1787 * @inheritdoc mw.inspect#runReports
1790 inspect: function () {
1791 var args
= slice
.call( arguments
);
1792 mw
.loader
.using( 'mediawiki.inspect', function () {
1793 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
1798 * On browsers that implement the localStorage API, the module store serves as a
1799 * smart complement to the browser cache. Unlike the browser cache, the module store
1800 * can slice a concatenated response from ResourceLoader into its constituent
1801 * modules and cache each of them separately, using each module's versioning scheme
1802 * to determine when the cache should be invalidated.
1805 * @class mw.loader.store
1808 // Whether the store is in use on this page.
1811 // The contents of the store, mapping '[module name]@[version]' keys
1812 // to module implementations.
1816 stats
: { hits
: 0, misses
: 0, expired
: 0 },
1819 experiment
: ( function () {
1820 var start
= ( new Date() ).getTime(), id
= 0, seed
= 0;
1823 id
= JSON
.parse( localStorage
.getItem( 'moduleStorageExperiment2' ) );
1824 if ( typeof id
!== 'number' ) {
1825 id
= Math
.floor( Math
.random() * Math
.random() * 1e16
);
1826 localStorage
.setItem( 'moduleStorageExperiment2', id
);
1832 // Unique identifier for this browser. This allows us to group all
1833 // datapoints generated by a particular browser, which in turn allows us
1834 // to see how the initial load compares to subsequent page loads.
1837 // Group assignment may be 0 (not in experiment), 1 (control group), or 2
1838 // (experimental group). Browsers that don't implement all the prerequisite APIs
1839 // (JSON and Web Storage) are ineligible. Eligible browsers have a 0.1% chance
1840 // of being included in the experiment, in which case they are equally likely to
1841 // be assigned to either the experimental or control group.
1842 group
: seed
=== 1 ? 1 : ( seed
=== 2 ? 2 : 0 ),
1844 // Assess module storage performance by measuring the time between this
1845 // reference point and the window load event.
1851 * Construct a JSON-serializable object representing the content of the store.
1852 * @return {Object} Module store contents.
1854 toJSON: function () {
1855 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
1859 * Get the localStorage key for the entire module store. The key references
1860 * $wgDBname to prevent clashes between wikis which share a common host.
1862 * @return {string} localStorage item key
1864 getStoreKey: function () {
1865 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
1869 * Get a string key on which to vary the module cache.
1870 * @return {string} String of concatenated vary conditions.
1872 getVary: function () {
1874 mw
.config
.get( 'skin' ),
1875 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
1876 mw
.config
.get( 'wgUserLanguage' )
1881 * Get a string key for a specific module. The key format is '[name]@[version]'.
1883 * @param {string} module Module name
1884 * @return {string|null} Module key or null if module does not exist
1886 getModuleKey: function ( module
) {
1887 return typeof registry
[module
] === 'object' ?
1888 ( module
+ '@' + registry
[module
].version
) : null;
1892 * Initialize the store.
1894 * Retrieves store from localStorage and (if successfully retrieved) decoding
1895 * the stored JSON value to a plain object.
1897 * The try / catch block is used for JSON & localStorage feature detection.
1898 * See the in-line documentation for Modernizr's localStorage feature detection
1899 * code for a full account of why we need a try / catch:
1900 * https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796
1905 if ( mw
.loader
.store
.enabled
!== null ) {
1910 if ( ( !mw
.config
.get( 'wgResourceLoaderStorageEnabled' ) && mw
.loader
.store
.experiment
.group
!== 2 )
1911 || mw
.config
.get( 'debug' ) ) {
1912 // Disabled by configuration, or because debug mode is set
1913 mw
.loader
.store
.enabled
= false;
1918 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
1919 // If we get here, localStorage is available; mark enabled
1920 mw
.loader
.store
.enabled
= true;
1921 data
= JSON
.parse( raw
);
1922 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
1923 mw
.loader
.store
.items
= data
.items
;
1928 if ( raw
=== undefined ) {
1929 // localStorage failed; disable store
1930 mw
.loader
.store
.enabled
= false;
1932 mw
.loader
.store
.update();
1937 * Retrieve a module from the store and update cache hit stats.
1939 * @param {string} module Module name
1940 * @return {string|boolean} Module implementation or false if unavailable
1942 get: function ( module
) {
1945 if ( !mw
.loader
.store
.enabled
) {
1949 key
= mw
.loader
.store
.getModuleKey( module
);
1950 if ( key
in mw
.loader
.store
.items
) {
1951 mw
.loader
.store
.stats
.hits
++;
1952 return mw
.loader
.store
.items
[key
];
1954 mw
.loader
.store
.stats
.misses
++;
1959 * Stringify a module and queue it for storage.
1961 * @param {string} module Module name
1962 * @param {Object} descriptor The module's descriptor as set in the registry
1964 set: function ( module
, descriptor
) {
1967 if ( !mw
.loader
.store
.enabled
) {
1971 key
= mw
.loader
.store
.getModuleKey( module
);
1974 // Already stored a copy of this exact version
1975 key
in mw
.loader
.store
.items
||
1976 // Module failed to load
1977 descriptor
.state
!== 'ready' ||
1978 // Unversioned, private, or site-/user-specific
1979 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user', 'site' ] ) !== -1 ) ||
1980 // Partial descriptor
1981 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
, descriptor
.messages
] ) !== -1
1989 JSON
.stringify( module
),
1990 typeof descriptor
.script
=== 'function' ?
1991 String( descriptor
.script
) :
1992 JSON
.stringify( descriptor
.script
),
1993 JSON
.stringify( descriptor
.style
),
1994 JSON
.stringify( descriptor
.messages
)
1996 // Attempted workaround for a possible Opera bug (bug 57567).
1997 // This regex should never match under sane conditions.
1998 if ( /^\s*\(/.test( args
[1] ) ) {
1999 args
[1] = 'function' + args
[1];
2000 log( 'Detected malformed function stringification (bug 57567)' );
2006 mw
.loader
.store
.items
[key
] = 'mw.loader.implement(' + args
.join(',') + ');';
2007 mw
.loader
.store
.update();
2011 * Iterate through the module store, removing any item that does not correspond
2012 * (in name and version) to an item in the module registry.
2014 prune: function () {
2017 if ( !mw
.loader
.store
.enabled
) {
2021 for ( key
in mw
.loader
.store
.items
) {
2022 module
= key
.substring( 0, key
.indexOf( '@' ) );
2023 if ( mw
.loader
.store
.getModuleKey( module
) !== key
) {
2024 mw
.loader
.store
.stats
.expired
++;
2025 delete mw
.loader
.store
.items
[key
];
2031 * Sync modules to localStorage.
2033 * This function debounces localStorage updates. When called multiple times in
2034 * quick succession, the calls are coalesced into a single update operation.
2035 * This allows us to call #update without having to consider the module load
2036 * queue; the call to localStorage.setItem will be naturally deferred until the
2037 * page is quiescent.
2039 * Because localStorage is shared by all pages with the same origin, if multiple
2040 * pages are loaded with different module sets, the possibility exists that
2041 * modules saved by one page will be clobbered by another. But the impact would
2042 * be minor and the problem would be corrected by subsequent page views.
2044 update
: ( function () {
2049 key
= mw
.loader
.store
.getStoreKey();
2051 if ( !mw
.loader
.store
.enabled
) {
2054 mw
.loader
.store
.prune();
2056 // Replacing the content of the module store might fail if the new
2057 // contents would exceed the browser's localStorage size limit. To
2058 // avoid clogging the browser with stale data, always remove the old
2059 // value before attempting to set the new one.
2060 localStorage
.removeItem( key
);
2061 data
= JSON
.stringify( mw
.loader
.store
);
2062 localStorage
.setItem( key
, data
);
2066 return function () {
2067 clearTimeout( timer
);
2068 timer
= setTimeout( flush
, 2000 );
2076 * HTML construction helper functions
2083 * output = Html.element( 'div', {}, new Html.Raw(
2084 * Html.element( 'img', { src: '<' } )
2086 * mw.log( output ); // <div><img src="<"/></div>
2091 html
: ( function () {
2092 function escapeCallback( s
) {
2109 * Escape a string for HTML. Converts special characters to HTML entities.
2110 * @param {string} s The string to escape
2112 escape: function ( s
) {
2113 return s
.replace( /['"<>&]/g, escapeCallback
);
2117 * Create an HTML element string, with safe escaping.
2119 * @param {string} name The tag name.
2120 * @param {Object} attrs An object with members mapping element names to values
2121 * @param {Mixed} contents The contents of the element. May be either:
2122 * - string: The string is escaped.
2123 * - null or undefined: The short closing form is used, e.g. <br/>.
2124 * - this.Raw: The value attribute is included without escaping.
2125 * - this.Cdata: The value attribute is included, and an exception is
2126 * thrown if it contains an illegal ETAGO delimiter.
2127 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
2129 element: function ( name
, attrs
, contents
) {
2130 var v
, attrName
, s
= '<' + name
;
2132 for ( attrName
in attrs
) {
2133 v
= attrs
[attrName
];
2134 // Convert name=true, to name=name
2138 } else if ( v
=== false ) {
2141 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2143 if ( contents
=== undefined || contents
=== null ) {
2150 switch ( typeof contents
) {
2153 s
+= this.escape( contents
);
2157 // Convert to string
2158 s
+= String( contents
);
2161 if ( contents
instanceof this.Raw
) {
2162 // Raw HTML inclusion
2163 s
+= contents
.value
;
2164 } else if ( contents
instanceof this.Cdata
) {
2166 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2167 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2169 s
+= contents
.value
;
2171 throw new Error( 'mw.html.element: Invalid type of contents' );
2174 s
+= '</' + name
+ '>';
2179 * Wrapper object for raw HTML passed to mw.html.element().
2180 * @class mw.html.Raw
2182 Raw: function ( value
) {
2187 * Wrapper object for CDATA element contents passed to mw.html.element()
2188 * @class mw.html.Cdata
2190 Cdata: function ( value
) {
2196 // Skeleton user object. mediawiki.user.js extends this
2203 * Registry and firing of events.
2205 * MediaWiki has various interface components that are extended, enhanced
2206 * or manipulated in some other way by extensions, gadgets and even
2209 * This framework helps streamlining the timing of when these other
2210 * code paths fire their plugins (instead of using document-ready,
2211 * which can and should be limited to firing only once).
2213 * Features like navigating to other wiki pages, previewing an edit
2214 * and editing itself – without a refresh – can then retrigger these
2215 * hooks accordingly to ensure everything still works as expected.
2219 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2220 * mw.hook( 'wikipage.content' ).fire( $content );
2222 * Handlers can be added and fired for arbitrary event names at any time. The same
2223 * event can be fired multiple times. The last run of an event is memorized
2224 * (similar to `$(document).ready` and `$.Deferred().done`).
2225 * This means if an event is fired, and a handler added afterwards, the added
2226 * function will be fired right away with the last given event data.
2228 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2229 * Thus allowing flexible use and optimal maintainability and authority control.
2230 * You can pass around the `add` and/or `fire` method to another piece of code
2231 * without it having to know the event name (or `mw.hook` for that matter).
2233 * var h = mw.hook( 'bar.ready' );
2234 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2236 * Note: Events are documented with an underscore instead of a dot in the event
2237 * name due to jsduck not supporting dots in that position.
2241 hook
: ( function () {
2245 * Create an instance of mw.hook.
2249 * @param {string} name Name of hook.
2252 return function ( name
) {
2253 var list
= lists
[name
] || ( lists
[name
] = $.Callbacks( 'memory' ) );
2257 * Register a hook handler
2258 * @param {Function...} handler Function to bind.
2264 * Unregister a hook handler
2265 * @param {Function...} handler Function to unbind.
2268 remove
: list
.remove
,
2272 * @param {Mixed...} data
2276 return list
.fireWith( null, slice
.call( arguments
) );
2285 // Alias $j to jQuery for backwards compatibility
2288 // Attach to window and globally alias
2289 window
.mw
= window
.mediaWiki
= mw
;
2291 // Auto-register from pre-loaded startup scripts
2292 if ( jQuery
.isFunction( window
.startUp
) ) {
2294 window
.startUp
= undefined;