Req.js - javascript lazy-loading and dependency managment made easy
Req.js is a simple, easy to use, full-featured library to handle lazy-loading and dependency management of Javascript.
It's a standalone javascript library (no dependencies) and defines only a single object Req in the global scope.
The concept is loosely based on JSLoad with some ideas from Dojo.require and early YUI 3.0 alphas thrown into the mix.
It's stable and thoroughly tested in production environment on over one hundred websites since 2008.
Key Features:
- Loads scripts asynchronously, with callbacks ...
- Ensuring all scripts execute in the correct order.
- Resolves and loads script dependencies.
- Handles circular dependencies gracefully.
- Avoids loading the same script twice.
- Supports custom checks for the pre-presence of each script asset.
- Allows mixing of local and remotely-hosted scripts.
- Supports nested calls.
- Allows for joining multiple assets into one "combo" HTTP request. (if supported by your server)
Also:
- Highly configurable.
- Cross-browser and no external dependencies.
- Fast (no evals)
- Tiny! (less than 1 kB gzipped)
Documentation
For a crash course in using Req.js, visit the demo page and inspect its source code.
Using the Req() function;
The library's core function, Req(), accepts any number of parameters.
The parameters may be a combination of:
String- Script URLs (either absolute or relative).Function- Callback functions that run as soon as the preceding scripts have loaded.Object- "Asset objects" that contain a script URL, charset info, dependency list, etc. (see below for more info).String- "Asset object ID"s that refer to a previously defined "Asset object".
All parameters are processed (i.e. loaded or run) in the order they're passed.
Req() maintains a single processing queue, so nested and/or independently repeated calls to Req() add their list of requirements to the front of the master queue -- like so:
Req(A, B, C, function(){ Req(D, E); }, F);
Req(G, H, I);
// Will be processed in this order:
// G, H, I, A, B, C, D, E, F
However, an optional first parameter of true will instruct Req() to append those parameters to the master queue -- like so:
Req(A, B, C);
Req(D, E, F);
Req(true, G, H, I);
// Will be processed in this order:
// D, E, F, A, B, C, G, H, I
"Asset objects" and Req.assets
Req() keeps a database of "asset objects" to track which scripts have been loaded, what their dependencies are, etc.
Every URL you pass as a parameter is automatically turned into a simple asset object and stored in Req.assets.
var myurl = 'http://code.jquery.com/jquery-latest.js';
alert ( typeof Req.assets[myurl] ); // 'undefined'
Req( myurl, mycallbackfn );
var myAsset = Req.assets[myurl];
alert ( typeof myAsset ); // "object"
alert ( myAsset.toSource() ); // { src: 'http://code.jquery.com/jquery-latest.js' }
You can store asset objects under a friendly id/label in the Req.assets database, and then refer to the asset using that label...
Req.assets['jQuery latest'] = {
src: 'http://code.jquery.com/jquery-latest.js'
};
Req( 'jQuery latest', mycallbackfn );
Asset object properties
Asset objects may contain the following properties:
src (String)
The actual URL to the javascript file.
Relative URLs get normalized with Req.fixUrl and Req.baseUrl - while URLs starting with http(s)://, /, and ./ are left untouched.
check (Function)
Function that returns true/false that determine whether this resource has already been loaded (via other means, such as, direct <script> tags, etc.)
req (Array)
List of assets objects (or asset IDs or URLs) that this asset depends on -- each of which may depend on other assets, etc. etc.
onload (Function)
Callback function (onload event handler) to run when the asset has loaded for the first time. (Useful for running inits methods.)
charset (String)
Character encoding of the script file - e.g. "utf-8". (Useful for mixed charset environments on old MSIE browsers - which ignore HTTP charset headers sent by server.)
join (Boolean - default: false)
Can this asset be joined with others into a single HTTP request (see Req.joinUrl and Req.getJoinUrl properties below).
id (String)
Friendly id/name for the asset. (Only used when passing asset objects as parameters to the Req() function)
Req configuration properties
Req.urlToken (default: '%{s}')
Replacement pattern for inserting relative asset.src urls into _baseUrl and _joinUrl
Req.baseUrl (default: '')
URL string used for normalizing relative asset URLs
Example: 'http://www.server.com/scripts/%{s}.js' ... the first occurrence of Req.urlToken gets replaced by an asset's .src value. (If the urlToken is missing, it gets appended to the URL.)
Req.joinUrl (default: '')
URL string used for constructing "combo" URLs for joining multiple assets into a single HTTP request.
Example: 'http://www.server.com/join/?%{s}' (See notes for Req.baseUrl above.)
Req.joint (default: '')
String token to separate the script URL-stubs/labels as they get inserted into the joinUrl.
Example: '|' ... which might result in a combo URL similar to this: 'http://www.server.com/join/?script1|script2|script3|script4'
Req.joinLim (default: 1)
Minimum number of consecutive join-able items needed for joining to occur. (Otherwise fall back to normal single-file loading.)
Req.fixUrl (Function)
Function used internally to normalize asset .src values into real URLs.
Accepts a raw URL as a parameter, and returns a "fixed" (normalized) URL.
Default behavior: Relative paths are supplemented with the baseUrl. Other URLs are left untouched.
Req.getJoinUrl (Function)
Function used to get the combo URL-stub/label for the given asset.
Accepts an asset object as a parameter, and returns a combo URL-stub/label, that gets inserted (along with others) into the joinUrl.
Default behavior: Returns whatever comes after baseUrl in a normalized asset URL.
Req.assets (default: {})
Container (Object) for Asset objects (see info in a previous chapter).
Req.charset (default: '')
A default charset="" attribute value for the <script /> elements when they're inserted into the page.
Downloads & Links
Download:
Documentation home:
Source updates:
Copyright & Licensing
Copyright (c) 2009 Már Örlygsson and Hugsmiđjan ehf.
Dual licensed under a MIT license and GPL 2.0 (or above).
More like this: English Entries, Javascript.
Már Örlygsson



Reader Comments (4)
Dinesh replies:
The Documentation home link is broken, the domain name does not have a period before net
December 27. 2009 kl. 11:14 GMT | #
Már replies:
@Dinesh thanks. I fixed the link.
December 28. 2009 kl. 10:29 GMT | #
Hannahrl replies:
I do really like your superior topic! Could you accomplish the good term paper as example? Because I do really know that a great custom media essays service could write term papers of supreme quality.
February 14. 2010 kl. 19:46 GMT | #
business loans replies:
Specialists claim that mortgage loans aid a lot of people to live the way they want, because they are able to feel free to buy necessary things. Furthermore, various banks give commercial loan for young and old people.
March 3. 2010 kl. 14:25 GMT | #