Modules/Resources

From CommonJS Spec Wiki
Jump to: navigation, search

STATUS: PROPOSAL

This a proposal for the specification of the "require.resource" method.

Contract

  1. 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.
  2. The callback function must be called as soon as all resources are available.
    1. 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:

  1. the return value of "require.resource" to allow for future modifications of the specification, notably the inclusion of promises,
  2. the means by which the resources are associated with an identifier and loaded, and
  3. 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.