You have been using a lot, but what is requirejs?

Requirejs is a module loader for js files and it loads them in asynchronous fashion. It is basically a client side implementation of AMD pattern(or asynchronous module definition).

By convention, we use the data-main attribute of the script tag that references the require js library.  It will load main.js file right after require.js is loaded and executed.

<script data-main="main" src="requirejs">

The two primary methods made available to us by require.js are require and define.

require generally, has two parameters: an array of modules, and an anonymous function to which the modules loaded in first parameter are passed as arguments.

main.js

require("jquery", 'hello', function($, message){

  $("#hi").html(message);

});

The location where main.js file is located becomes the root of the module.

The first parameter of define is name of the module. However, if we are using conventional file name, that can be excluded.

The second parameter can be array of modules which are required by the current module. which can be passed as arguments to third parameter which is an anonymous function.

hello.js

define("hello", [], function(){

  return "Hello World";

};
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s