Saif Bechan
Saif Bechan

Reputation: 17121

Have require.js load my files only when I actually need them

I know this is the whole point of require.js, but it does not behave this way in my situation.

I am creating a single page Backbone.js application. The main entry point to the application is trough a router. Let's say I have 3 routes:

users: function(){
    require('users');
},
products: function(){
    require('products');
},
groups: function(){
    require('groups');
},

Based on the function I call I want to load the file, but require.js does not do this.

Instead it downloads all the files for my complete website everywhere there is a require. I haven't even called the function but it loads the file.

Is there a way to have require.js behave as it should, and download the file only when I am actually inside the function.

Upvotes: 1

Views: 1631

Answers (1)

Gohn67
Gohn67

Reputation: 10638

You can basically do what you have in your code snippet. It'd look something like this:

users: function(){
    require(['users'], function(Users){
        //Code
    });
},
products: function(){
    require(['products'], function(Products){
        //Code
    });
},
groups: function(){
    require(['groups'], function(Groups){
        //Code
    });
},

Upvotes: 6

Related Questions