Modules/Resources
From CommonJS Spec Wiki
< Modules
STATUS: PROPOSAL
This a proposal for the specification of the "require.resource" method.
Contents
Contract
- A "resource" function is defined as a property of the value of the free variable "require" provided in the module scope. "require.resource" accepts either a single resource identifier or an array of resource identifiers as the first argument and a callback function as second argument.
- The callback function must be called as soon as all resources are available.
- The callback function must be passed the data of the named resource or, if multiple resources were named, an object containing the data of each named resource and keyed each resource identifier, as its first argument.
Unspecified
This specification leaves the following important points of interoperability unspecified:
- the return value of "require.resource" to allow for future modifications of the specification, notably the inclusion of promises,
- the means by which the resources are associated with an identifier and loaded, and
- the presence of a timeout.
Sample Code
- messages.json
{ "hello": "Hello World!" }
- entry.html
<div class="entry"> <h1>{{title}}</h1> <div class="body"> {{body}} </div> </div>
- program.js
// Single resource require.resource( 'messages', function( messages ) { messages; // Object containing `hello` message }); // Multiple resources require.resource( ['messages', 'templates'], function( resources ) { resources.messages; // Object containing `hello` message resources.templates; // Object containing `entry` template });
Notes
- MediaWiki's ResourceLoader supports the concept of bundling scripts, styles and messages together in a single module.