The following is a draft working towards a proposal for adoption as a Wikipedia
policy, guideline, or process. The proposal must not be taken to represent consensus, but is still in development and under discussion, and has not yet reached the process of gathering consensus for adoption. Thus references or links to this page should not describe it as policy, guideline, nor yet even as a proposal. |
The previous version of this draft is available here |
Script libraries are bits of Javascript code intended to be easily reused by userscripts.
Script libraries add an object to the Window object. This object contains one or more pieces of code intended to be used by other scripts – typically functions or classes.
Window.libSomethingUseful = {
doThis: function(param) {
// ...
return something;
},
doThat: function(p1, p2) {
// ...
return somethingElse;
}
}
The name used should be quite unique, and unlikely to be unintentionally overridden by other scripts.
To minimise the number of network requests, related functionality should all be contained within a single module, rather than several small modules. To minimise the size of network requests, unrelated functionality should be split between separate modules, rather than one huge module.
Script libraries should, if possible, avoid having dependencies themselves. This allows scripts to easily use them:
mw.loader.getScript( /* script url */ ).then(function() {
// the library is now available on the Window object
// ...
} );
If necessary, then there are two options for handling dependencies:
mw.loader.using( /* dependencies */ ).then(function(
mw.loader.getScript( /* script url */ ).then(function() {
// the library is now available on the Window object
// ...
} );
} );
mw.loader.getScript( /* script url */ ).then(function() {
// A Promise is now available on the window object.
$.when( /* library Promise */ ).then(function(libraryName) { // script gets to decide what to call the library
// the library is now available, as a variable scoped to this function
// ...
} );
} );
Should be required. Requires a little bit of effort to set up, but invaluable for making changes/updates much less likely to break things. Which could break a lot of things for a lot of users, if the library becomes widely used. Examples using QUnit: User:Evad37/rater/test.js, User:Evad37/Covery/sandbox.js
Should script modules be stored in a pseudo-namespace like MediaWiki:Script module/? This means that only code approved by Interface Admins can be exported to other scripts, who could require non-minor updates to pass a WP:Code review.
Module authors wanting to add or update a script module would use an edit request, or post a request at the Interface administrators' noticeboard.