Splitting Requrie.js optimized file into multiple bunches

Let’s say that you use Require.js in your project. On production you use r.js optimizer in order to have one single file. At some point your optimized file may became huge (few Mb if not gziped) and then you’ll want to split common/critical functionality from secondary functionality that may be deferred.

For example let’s take following project structure:

  • main.js
  • utils/
    • router.js
    • renderer.js
  • vendor/
    • jQuery.js
  • modules/
    • chat.js
    • page.js

In this case chat.js can be considered as secondary functionality. Now let’s see how to split critical and secondary functionality so that loading secondary functionality could be deferred.

Splitting optimized file into multiple bunches

Splitting optimized file into multiple files is builtin r.js and can be used by adding modules attribute to Require.js configuration:

  appDir: './'
, mainConfigFile: './main.js'
, dir: './public'
, modules: [{
    // First define secondary functionality
    name: 'modules/chat.js'
  , exclude: ['utils/renderer.js', 'vendor/jQuery.js']
  }, {
    // Now define critical functionality
    name: 'main.js'
  , exclude: ['modules/chat.js']

Now when running r.js optimizer we’ll get 2 files as output: main.js and modules/chat.js. The only thing left is to require chat.js file when it will be necessary or when main.js finished loading.

Loading chat.js when main.js fihished loading:

// main.js
, 'renderer.js'
, 'vendor/jQuery.js'
, 'modules/page.js'
], function(Router, Renderer, jQuery, PageModule) {
  // Run some initialization code

  // Now load chat
  require(['modules/chat.js'], function(ChatModule) {
    // Run chat initialization

Loading chat.js only when it is required (ex. on click) is the same as previous example. For that require(['modules/chat.js'], function(){}) should be run on desired event.

Splitting common and page-specific functionality in multi-page projects

If you’re looking for splitting functionality for multi-page projects then you may want to take a look at requirejs/example-multipage and requirejs/example-multipage-shim. This examples use almost the same logic. The only difference is the order in which files are required: each page has a file with its specific functionality that requires common functionality.