Open main menu

Snippets/Load an additional JavaScript or stylesheet file on all pages

< Snippets
How to use Snippets
List of Snippets
Crystal Clear action run.png
Load an additional JavaScript or stylesheet file on all pages
Language(s): PHP
Compatible with: MediaWiki 1.23+ 

You can easily add snippets of JavaScript and CSS by editing special MediaWiki pages as described in Manual:Interface/JavaScript and Manual:Interface/Stylesheets. However, if you want to include additional scripts and stylesheet files without put their contents on wiki pages, because you're using an external version control system or want to edit those files directly, this is a guide about how to include them.

This also solves the problem of CSS and Scripts not loading on special restricted pages like preferences or the login page.

Contents

Scripts hosted on the same wiki/serverEdit

PreparationEdit

It's recommended to put your custom CSS and JavaScript files on a specific location, so you can track them during upgrades. In this example, those files will be inside a customizations folder, placed inside the MediaWiki installation folder.

We're going to use 3 files in this example:

  • skin.css: A stylesheet we want to load on all skins.
  • skin-vector.css: A stylesheet we want to load only on the Vector skin.
  • skin.js: A JavaScript file we want to load on all skins.

CodeEdit

This is an example code to add at the bottom of LocalSettings.php :

$wgResourceModules['zzz.customizations'] = array(
	'styles' => "skin.css", // Stylesheet to be loaded in all skins
	// Custom styles to apply only to Vector skin. Remove if you don't use it
	'skinStyles' => array(
		'vector' => 'skin-vector.css',
	),
	// End custom styles for vector
	'scripts' => "skin.js", // Script file to be loaded in all skins
	'localBasePath' => "$IP/customizations/",
	'remoteBasePath' => "$wgScriptPath/customizations/"
);

function efCustomBeforePageDisplay( &$out, &$skin ) {
	$out->addModules( array( 'zzz.customizations' ) );
}

$wgHooks['BeforePageDisplay'][] = 'efCustomBeforePageDisplay';

Scripts hosted externallyEdit

To add a script hosted externally, include it from the BeforePageDisplay hook:

$wgHooks['BeforePageDisplay'][] = function( OutputPage &$out, Skin &$skin ) {
	$out->addScriptFile( 'https://www.example.org/awesomescript.js' );
};

See alsoEdit