Skip to content

Off package modules

azproduction edited this page Jan 28, 2013 · 1 revision
  • Flags: async, race, cache_async, async_plain, async_plainonly

You can build async LMD package. (Disabled by default)

Then your packages can require off-package modules from http server. Build LMD package using async: true flag. LMD loader now can require javascript FunctionsExpressions, JSON or template strings asynchronously. LMD parses file content depend on Content-type header. You must work online using HTTP server for correct headers, if you work offline (using file: protocol) then Content-type header will be INVALID so all modules will be strings.

Note

  • If you use file: protocol then all modules will be strings
  • LMD loader uses simple RegExp /script$|json$/ with Content-type to determine the kind of content and eval it (if json or javascript) or return as string
  • If all you modules are in-package then set async flag to false (300 bytes less)
  • If async require fails (status code will be >= 400) loader will return undefined (LMD doesn't re-request on error)
  • If you are performing parallel loading of the same resource add race: true (Disabled by default) flag to prevent duplication of requests.
  • You can set both flags cache and cache_async to true to enable localStorage cache for require.async() (see Local Storage cache)
  • You can require plain off-package modules by declaring one of flags async_plain or async_plainonly
// Valid
(function (require, exports, module) {
    /* Module content */
})

// Invalid! - parse error in loader's eval
function (require, exports, module) {
    /* Module content */
}

// Bad but valid: module name will leak in global variables
function module(require, exports, module) {
    /* Module content */
}

Example

(function main(require) {

    // async require of off-package module
    require.async('/css/_engine.css', function (css) {
        console.log('1', css.length); // result

        // require of module loaded async (already registered)
        console.log('2', require('/css/_engine.css').length);

        // require of in-package module
        console.log('3', require('pewpew'));
    });

    // async require of in-package module
    require.async('pewpew', function (pewpew) {
        console.log('4', pewpew);
    });
})

See examples/demos/basic for real life example

Clone this wiki locally