Requirejs load all or a part of dependence object?

47 Views Asked by At

I am creating a javascript module which store some functions used by some web pages. For example:

define(['...',...], function() {
    return {
         func1: function(){...},
         func2: function(){...},
         func3: function(){...},
      }
});

I have a module on page1.html just use func1, other module on page2.html just use func2, so on. In this case, I wonder requirejs load required functions or load whole object.

I intend to build modules which are shared among web pages. If requirejs load whole object, I'm afraid that it will take more time to download unnecessary scripts. Do you any idea about this problem?

1

There are 1 best solutions below

0
On

Grouping all your methods in one module will result in require returning the whole object yes. If you want to only load func1 on page1, func2 on page2 etc then you will be better off declaring each in its own separate module and file. Then load each module when necessary.

// func1.js
define(['...'], function(){
    return {
        func1 : function(){}
    }
})

// func2.js
define(['...'], function(){
    return {
        func1 : function(){}
    }
})

The requirejs documentation points to a great example for multipage-apps: https://github.com/requirejs/example-multipage

Note: in many cases it is better to actually load all your scripts in one http request rather than making asynchronous requests for each file in your application. Many large application uses r.js to bundle their scripts into just a few files.