RequireJS - Defining Function


The define() function can be used to load the modules (module can be an object, function, class or a code which is executed after loading a module). You can load different versions of the same module in the same page. The different versions can be analyzed in the same order, even if they are loaded in a different order.


define(['module1', 'module2'], function (module1, module2) {
   //define the module value by returning a value
   return function () {};

You can pass a list of module names when you define a module and RequireJS can be used to retrieve these modules before executing the module. These modules can be passed as parameters of the definition function.


The following example shows the usage of the define() function while loading the modules. Create an html file with the name index.html and place the following code in it −

<!DOCTYPE html>
      <title>Define() Function</title>
      <script data-main = "main" src = "require.js"></script>
      <h2>RequireJS Define() Function Example</h2>

Create a js file with the name main.js and add the following code in it −

define(function (require) {
   var myteam = require("./team");
   var mylogger = require("./player");
   alert("Player Name : " + myteam.player);

Now, create two more js files with the names team.js and player.js and place the following code respectively −


   player: "Sachin Tendulkar",
   team : "India"


define(function (require) {
   var myteam = require("./team");

   return {
      myfunc: function () {
         document.write("Name: " + myteam.player + ", Country: " +;


Open the HTML file in a browser; you will receive an output as in the following screenshot −

RequireJS Define Function

Click on the "OK" button, you will get another output from modules −

RequireJS Define Function