Basics of Require.JS For Web Development


In this article we will see the basics of the "Required.JS" plugin and how to implement the various options of "Required.JS".

"RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino, Node and jQuery. Using a modular script loader like RequireJS will improve the speed and quality of your code."

Step 1

First let's understand the existing problem with a traditional approach and solution structure. We have an ASP.NET master page which has JavaScript references as mentioned below.


For Demo purpose, I have created two pages using "prettyphoto" and "datapick" JavaScript files. Once we run the test pages, we will get the results as below.

PrettyPhoto sample page


Calendar Page


As we will see, the functionalities for the pages are working fine. But the problem is, in the calendar page I didn't use "PrettyPhoto.js" and in the PrettyPhoto page  didn't use "datepick.js". We have simple a page which doesn't use any JavaScripts, but all scripts are loaded because it's referenced in the Master page.


Step 2

Download the sample code and the JavaScript file. Add the js files to the solution.

Comment the existing script references in the Master page and add the Require JS file. The data-main attribute on the script tag for require.js tells Require JS to load the scripts/main.js file. Require JS will load any dependency that is passed to require () without a ".js" file from the same directory as the one used for data-main.


In this article we didn't used the main.jS file. Now in the default page we removed the unnecessary JavaScript files that were loaded.


In the calendar page, just change the script as mentioned below to load only the required "datapick.js" file.


In the calendar page we will see that only the Require JS, main.js and datepick.js files are loaded.


In the Prettyphoto page the script to load only the required "PrettyPhtoto.JS" was also changed.




Using Require.JS, we will resolve the JavaScript dependency and improve the performance.

Similar Articles