Basics of Require.JS For Web Development

Introduction

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.

RQRJS1.jpg

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

RQRJS2.jpg

Calendar Page

RQRJS3.jpg

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.

RQRJS4.jpg

Step 2

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

http://requirejs.org/docs/jquery.html

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.

RQRJS5.jpg

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.

RQRJS6.jpg

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

RQRJS7.jpg

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

RQRJS8.jpg

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

RQRJS9.jpg

RQRJS10.jpg

Summary

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

Up Next
    Ebook Download
    View all
    Learn
    View all