Jump to content

Snippets/Load modules and external scripts

From mediawiki.org
How to use Snippets
List of Snippets
Load modules and external scripts
Language(s): JavaScript
Compatible with: MediaWiki 1.17+ 

Code

[edit]
/**
 * Load both RL modules and external scripts with a unified interface
 *
 * @source https://www.mediawiki.org/wiki/Snippets/Load_modules_and_external_scripts
 * @version 4
 */
function loadScripts(scripts) {
	var deferreds = [];
	$.each(scripts, function (i, script) {
		// External script, use $.getScript
		if (script.match(/^(https?:|\/\/)/)) {
			deferreds.push($.getScript(script));
		// Use mw.using, convert callbacks to Deferreds
		} else {
			var d = $.Deferred();
			// TODO: make only one mw.loader.using call, passing an array of module names
			mw.loader.using(script, d.resolve, d.reject);
			deferreds.push(d);
		}
	});
	return $.when.apply($, deferreds);
}

Example

[edit]

scripts is an array of RL module names and external script URLs. Example:

var requires = [
    'jquery.ui.button',
    'jquery.ui.dialog',
    'mediawiki.api',
    '//en.wikipedia.org/w/index.php?title=User:Yuvipanda/underscore.js&action=raw&ctype=text/javascript'
];
loadScripts(requires).done(function () {
    // Do stuff here
});