Ryan Hu
Ryan Hu

Reputation: 332

Requirejs load different js file inside define()

My webpage has different js components that handles different business logic. And I'm using RequireJS to manage dependencies. I want to dynamically load the component which is needed.

For example:

define(['something'],function(something){
    var processor;
    if(userRole === "student"){
        //I want to dynamically load studentProcessor.js here;
    }
    else if(userRole === "teacher"){
        //I want to dynamically load teacherProcessor.js here;
    }     

    processor.process();
});

Really appreciate if anyone can tell me what is the best way to handle this.

Upvotes: 1

Views: 52

Answers (1)

GOTO 0
GOTO 0

Reputation: 47672

I think the cleanest way to handle this is having a sort of mapping from user roles to processors. Then in your function, you still need to check that userRole is set, and a processor for the role is defined.

// This is where processors are associated to user roles.
var roleToProcessorMapping =
{
  student: './studentProcessor.js',
  teacher: './teacherProcessor.js'
};

define(['something'],function(something){
    if(userRole){
      var processorPath = roleToProcessorMapping[userRole];
      if(processorPath){
        require([processorPath], function(processor){
          processor.process();
        });
        return;
      }
    }
    // handle error
});

Upvotes: 3

Related Questions