Created
March 31, 2011 15:50
-
-
Save micmath/896624 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Make two file requests for two modules | |
---- | |
This is the current state of our RequireJS usage. The map is automatically | |
generated by the BBC Mapper application. This is flexible and it works, however | |
it requires two downloads from the server. | |
// map module ids to urls | |
require({ | |
'swfobject-1': 'exact/path/1.2.3/swfobject.js', | |
'jquery-1': 'exact/path/1.5.2/jquery.js' | |
}); | |
// require module ids | |
require( | |
['swfobject-1', 'jquery-1'], | |
function(swfobject, $) { | |
// callback in here | |
} | |
); | |
Change the map and make one file request for two modules | |
---- | |
A niave approch to reducing the number of downloads from two to one. The | |
disadvantage is that it requires modifying (possibly overwriting) the URL values | |
in the map. In addition the size of the map bloats very quickly. | |
This works because on the server there is a process named "cat.php" that simply | |
joins the two files together into one. Care must be taken to keep the order | |
of the individual module URLs in the query string consistent, to allow caching | |
of the returned script. | |
require({ | |
'swfobject-1': 'cat.php?exact/path/1.2.3/swfobject.js&exact/path/1.5.2/jquery.js', | |
'jquery-1': 'cat.php?exact/path/1.2.3/swfobject.js&exact/path/1.5.2/jquery.js' | |
}); | |
require( | |
['swfobject-1', 'jquery-1'], | |
function(swfobject, $) { | |
// callback in here | |
} | |
); | |
It's a plug in! | |
---- | |
Here the map is left untouched, instead the package contents are specified via | |
a plugin. The advantage is that the map continues to work the same as always. | |
However, since require can only return one thing from a call to require a module | |
(or in this case a package of modules), we must change the parameters of our | |
callback to accept a single package, rather than two separate modules. | |
This works because, behind the scenes, our pkg! plugin consults the map and then | |
converts the request for "swfobject-1+jquery-1" into a single require for | |
the "cat.php?exact/path/1.2.3/swfobject.js&exact/path/1.5.2/jquery.js" URL. The | |
plugin follows a convention that guarantees the individual module URLs in the | |
querystring are always in the same order to allow caching of the returned script. | |
require({ | |
'swfobject-1': 'exact/path/1.2.3/swfobject.js', | |
'jquery-1': 'exact/path/1.5.2/jquery.js' | |
}); | |
require( | |
['pkg!swfobject-1+jquery-1'], | |
function(pkg) { | |
// use pkg.swfobject | |
// use pkg.jquery | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment