JavaScript require() on client side

Solution 1:

You should look into require.js or head.js for this.

Solution 2:

I've been using browserify for that. It also lets me integrate Node.js modules into my client-side code.

I blogged about it here: Add node.js/CommonJS style require() to client-side JavaScript with browserify

Solution 3:

If you want to have Node.js style require you can use something like this:

var require = (function () {
    var cache = {};
    function loadScript(url) {
        var xhr = new XMLHttpRequest(),
            fnBody;
        xhr.open('get', url, false);
        xhr.send();
        if (xhr.status === 200 && xhr.getResponseHeader('Content-Type') === 'application/x-javascript') {
            fnBody = 'var exports = {};\n' + xhr.responseText + '\nreturn exports;';
            cache[url] = (new Function(fnBody)).call({});
        }
    }
    function resolve(module) {
        //TODO resolve urls
        return module;
    }
    function require(module) {
        var url = resolve(module);
        if (!Object.prototype.hasOwnProperty.call(cache, url)) {
            loadScript(url);
        }
        return cache[url];
    }
    require.cache = cache;
    require.resolve = resolve;
    return require;
}());

Beware: this code works but is incomplete (especially url resolving) and does not implement all Node.js features (I just put this together last night). YOU SHOULD NOT USE THIS CODE in real apps but it gives you a starting point. I tested it with this simple module and it works:

function hello() {
    console.log('Hello world!');
}

exports.hello = hello;

Solution 4:

I asked myself the very same questions. When I looked into it I found the choices overwhelming.

Fortunately I found this excellent spreadsheet that helps you choice the best loader based on your requirements:

https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ