Boba Fett likes JS
Boba Fett likes JS

Reputation: 767

RequireJS plugin, load files on demand

I have RequireJS implemented fine, and a Grunt based build process which is optimizing the all the JS files app into one file via r.js which is also working fine. All my app files are concatenated into one big JS file for efficient production deployment. Now I'm having the following requirements: I need to write a plugin for requirejs, that will not load(not include the file) into the optimized file in the build process, but will required on demand: Meaning in my code I'll have:

var myObj = require("myplugIn!jsFile");

So in the end when this line runs, it will runs in 2 options:

  1. on build process, the file is not included in the optimized file
  2. The application is running, it will be request the file on demand.

I wrote the following plugin, but is not working:

define(function () {
"use strict";
return {
    load : function (name, req, onload, config) {
        // we go inside here we are running the application not in build process
        if (!config.isBuild) {
            req([name], function () {
                    onload(arguments[0]);
                });                
        } 
    }
};
});

What I'm missing here.

Upvotes: 0

Views: 478

Answers (2)

Boba Fett likes JS
Boba Fett likes JS

Reputation: 767

It was more simpler that I though, if helps someone, I'm posting the solution, I create a plugin , that in build process return nothing and in run time, returns the required file, hope helps someone.

define(function () {
"use strict";

return {
    load : function (name, req, onload, config) {
        if (config.isBuild) {
            onload(null);
        } else {
            req([name], function () {
                onload(arguments[0]);
            });
        }
    }
};

});

Upvotes: 0

Tomas Kirda
Tomas Kirda

Reputation: 8413

In your build configuration you can exclude files that you don't want to bundle. They will still be loaded on demand when needed. You may also do something like this:

define(function (){
    // module code...

    if (condition){
        require(['mymodule'], function () {
            // execute when mymodule has loaded.
        });
    }

}):

This way mymodule will be loaded only if condition is met. And only once, if you use same module dependency elsewhere it will return loaded module.

Upvotes: 2

Related Questions