Using the Dojo loader to include your own JavaScript module is very handy, and also works around several problems related to loading JavaScript code directly via the <script> tag. Often, however, you want to be able to load your modules across domains, so you need to write them in xd fashion. In itself, it's not a big issue as, with Dojo 1.2.0, a non-xd code such as this:
(function(){
dojo.provide("cryo.Tree");
dojo.provide("cryo.ForestStoreModel");
dojo.require("dijit.Tree");
dojo.declare("cryo.ForestStoreModel", dijit.tree.ForestStoreModel, {
// class definition
});
dojo.declare("cryo.Tree", dijit.Tree, {
// class definition
});
})();
just needs to become as follows to work with the Dojo cross-domain loader:
dojo._xdResourceLoaded(function(){ return {
depends: [
["provide", "cryo.Tree"],
["provide", "cryo.ForestStoreModel"],
["require", "dijit.Tree"]
],
defineResource: function(dojo) {
dojo.provide("cryo.Tree");
dojo.provide("cryo.ForestStoreModel");
dojo.require("dijit.Tree");
dojo.declare("cryo.ForestStoreModel", dijit.tree.ForestStoreModel, {
// class definition
});
dojo.declare("cryo.Tree", dijit.Tree, {
// class definition
});
})();
Easy enough, but what usually happens is that you work with non-xd files while developing, while using the cross-domain features in production. Or maybe the opposite. Or something similar. Anyhow, in this case you most likely don't want to maintain two copies of the same JavaScript module where only header and footer are different. For sure I don't, so I wrote a small Perl script which converts non-xd modules to xd-enabled ones automatically by performing the following tasks:
- It parses
dojo.requireanddojo.providestatements in order to create the xd header. - It substitutes the header with an xd one containing the information obtained in the parsing operation.
- It substitutes the closing parentheses with others which match the new header.
OK, I know, there's also the Dojo Build System, but I didn't want to install Ant and a ton of Java-related dependencies for a task which requires 20 lines of code.
This script is a quick hack so it has caveats:
- It's a quickly (and therefore poorly) coded dirty hack.
- Read the code before using it and edit it if needed.
- It's supposed to work if the code is formatted a bit differently than the examples above, but there's no guarantee - I just tried out some variations.
- It produces xd code only suitable for Dojo 1.2.0 (but changing it for 1.1.1 is trivial)
On the other hand, using it makes no harm to your existing code: it will either work and produce (possibly broken) output files, or produce no files at all. So, I would say it is safe to try it.
Usage:
make_xd.pl file1.js file2.js ... filen.js
You can pass one or more files on the command line: the script will produce filename.xd.js starting from filename.js, which is left untouched.
Click here to download the script.
If you improve this script, please let me know.

