javascriptrequirejsgrunt-contrib-requirejs

Concatenate modules in RequireJS


I am using RequireJS to modularize my code. The website I am using will have several distinct page categories. For each one of them I want to load general JS file with all the dependencies that exist across all page categories, jQuery being most obvious one. I have managed to do that already.

For the rest of the pages, I want to have separate JS files. Each page has its own module but I am thinking that it would make more sense if I download several pages modules all at once and this way when the user comes to other pages, he will have the JS file already cached and won't have to download.

For now I tried to concatenate these modules which did work rather well. However, I am not sure how to load the specific module from a file. So far I am doing this:

require(['./js/common'], function (common) {
    require(['public']);
});

common is the dependencies file and public is my concatenated file with all the dependencies. Inside it has modules for each page but I don't know how to call a specific one. Any ideas?


Solution

  • Take a look at the bundles option for RequireJS' runtime configuration. In your case it would be something like:

    bundles: {
        public: ['mod1', 'mod2', ...] 
    }
    

    I've used mod1, mod2 because I don't see the name of the actual modules in your question but what you'd want there are the names of the modules inside the public bundle and that you want to load individually. With this, RequireJS will know that when you want to load such module, it has to get them from public instead of searching for them indivdually.

    Then you should be able to change your loading code to:

    require(['./js/common'], function (common) {
        require(['mod1']);
    });
    

    Again, mod1 is for illustration.