Using Resource Loader to add JavaScript and CSS modules in Extension

The Mediawiki extensions are also a part of web development so they need JavaScript and CSS support too, for the same you can and you should use Resource Loader module. This tutorial demonstrate the use of ResourceLoader module and how to use that in extension development.


We have already seen the basics of MediaWiki extensions if you are new then please go through the previous two tutorials, to know the basic know how. Please see the index below for the series.

In this part we are going to demonstrate the use of Resource Loader module, which is used to include JavaScript, CSS or Messages module in the extension. So, like in earlier tutorial or in general first of all we need to register the module with the extension. Following is the Index of this series.

MediaWiki Extension – How to Develop custom extension in MediaWiki
MediaWiki Extension – localization of MediaWiki Extension
MediaWiki Extension – Using Resource Loader to inject JavaScript and CSS
MediaWiki Extension – Enabling use of Ajax in Extension

To register the module we use the $wgResourceModules array variable to name the module, and add all our resources in it, as an associative array, Mainly following modules are involved.

$wgResourceModules['ext.DemoExtension'] = array(
	"scripts"=>"resources/js/demo.js",
	"styles"=>"resources/css/demo.css",
	"dependencies"=>array("jquery"),
	'localBasePath'=> __DIR__,
   'remoteExtpath'=>'DemoExtension'
);

If you are working with single JavaScript/CSS file you can mention it as a string only but if there are more than one file you can write it as an array, like the way we have done with dependencies. localBasePath is the path from where the relative path for scripts and styles is defined. remoteExtpath is the directory name for the extension.

In the JavaScript and Css files we have written our test code. as shown in following code snippet.

console.log("Hey, My JS is working!");

.highlight-green{
	background-color:#0f0;
}

Finally output the modules on the extension page using output page object. just as shown in the code below.

class DemoExtension {
    public static function injectHTMLInEditor(&$editPage,&$output) {
		$output->addModules("ext.DemoExtension");
		$editPage->editFormTextAfterWarn .='<div id="demoDiv" class="highlight-green">****Hi This is HTML Injected via Demo Extension****</div>';
		$editPage->editFormTextAfterWarn .='This Message Comes From The localization Files:'.wfMessage('the-key');
		return true;
    }
}

Okay, so we are all set, now we should be able to see the outcome on the intended page.

Media Wiki Extension Resource Loader Module

In the next tutorial you can read about the use of Ajax feature to give more exclusive features to your extension:Using Ajax in MediaWiki extensions.