Q:

RequireJS - Load module on the fly

I am currently a beginner on RequireJS and i am a bit in trouble with the AMD concept, especially the way that RequireJS is defining it.
My aim is to build a smart Loader that call the specific Parser he needs.

To summarize my needs :
(A) I create my loader : new Loader(source)
(B) source represents the data to load. That's a simple string.
(C) A Loader object is created. It executes some algorithm to decide what is the best Parser to use. Eventually, it downloads the parser from a remote location. Finally, it loads the parser dynamically.

My problem is this one : How can I load a module/plugin without expliciting it in the define? I cant set it in the define([theParserHere]) because I am unable to know which Parser is needed.

A:

The require function sounds like it could be used for your purposes. It allows for loading of modules, but not defining a new module.
Your loader could call a function such as the following to load a module dynamically when needed:
function loadParser(name, fn) {
    require(["parsers/" + name], fn);
}

name would be the name of the parser or a path or something (note that my path was just an example) and fn is a callback to call when the loading has been completed. The first argument to the function would be the loaded module.
This function could be placed in your loader object or just sit inside the define:
define(function () {

    function Loader(text) {
        this.text = text;

        this.parser = null;
        this.loadParser();
    }

    Loader.prototype.loadParser = function () {
        var self = this;
        var parserName = this.getParserName();
        require(["parsers/" + parserName], function (Parser) {
            self.parser = Parser;
            self.parse();
        });
    }

    Loader.prototype.getParserName = function () {
        //mystery logic to determine language...
        return "some-parser-name";
    }

    Loader.prototype.parse = function () {
        if (!this.parser) {
            throw "No parser loaded";
        }
        //do your parsing logic...
    }

    return Loader;

});

Now, if I were actually doing this, I would use Q or jquery deferreds or something for resolving the parser inside the require callback function instead of all that function calling.

