Build a simple client-side MVC app with RequireJS

Tarun Kumar Chatterjee
 
Net – Technology Specialist
June 26, 2017
 
Rate this article
 
Views
3232

RequireJS is an implementation of AMD (Asynchronous Module Definition), an API for declaring modules and loading them asynchronously on the fly when they’re needed.

We instantly have a problem, our custom jQuery plugins will not work, as jQuery itself has not be loaded yet. Sure we could move the jQuery script tag to be before the custom jQuery plugins, which would indeed fix the problem this once. This is however a very isolated small use case, which is not really the norm on large scale applications, where we may have many many related files which all have dependencies. This is where RequireJs can help.

Using RequireJs we are able to specify things like:

· Define a module

· Require a module 

· The modules dependencies (via a RequireJs config called  shim)

· The module paths 

require() vs. define():

We can use both require() and define() to load module dependencies. The require() function is used to run immediately, where as define() is used to define modules which may be used from multiple locations.

We can see that we are actually configuring RequireJs for certain things, such as:

· BaseUrl: Specifies the base path for all the scripts, you can still use RequireJs with relative paths, but this is its base path

· Paths : Is a map of named paths where we specify a well known name and a path

· Shim: Is a map of files, and their dependecies. What this does is that is gives a hint to RequireJs about the required module dependencies such that RequireJs will then know to load them in the correct order. Remember that RequireJs uses a technique which means modules are loaded asychronously. It can be seen from the example above that “jquery.appender” and “jquery.textReplacer” are dependent on jQuery. As such RequireJs will load that first.It may seem that we are just swapping the evils of having the correct javascript imports in the html in the correct order for this, but what we do get from RequireJs is that modules are loaded asychronously

Let me create a simple asp.net web application and implement the RequireJS and the details are as follows:

Download the Jquery and AngularJS from nuget by using the below commands

PM> Install-Package jQuery

PM> Install-Package angularjs

PM> Install-Package RequireJS

Now add some custom scripts, following are the Scripts hierarchy snapshots and codes:

clip_image002

Config.js code:

 requirejs.config({
     
     baseUrl: 'Scripts/js',
     paths: {
         angular: 'angular.min',
         jquery: 'jquery-3.0.0.min',
         mootools: 'mootools-core-1.4.5-full-nocompat',
         methods: 'CustomScript/method'
     }
     //,shim: {
     //        "angular": { deps: ["mootools"] }
     //}
 })
 

JQueryFile.js code:

 define( ['jquery', 'methods'], function ($, methods) {
     
     //$('body').html('Hello, from other side !!!!');
     $('#clickMe').click(function () {
         methods.changeHTML('Clicked');
         methods.showAlert('Clicked');
 
         require(['CustomScript/CusScript']);
     })
 });  
 

Method.js code:

 define(['jquery','angular'], function ($,angular) {
     var methods = {};
 
     methods.changeHTML = function(argument)
     {
         $('body').html(argument);
     }
     methods.showAlert = function (argument) {
         alert(argument);
     }
     return methods;
 }); 
 

CusScript.js code:

 define(['mootools'], function (mootools) {
 });
 

Next to create RequireJSTest.html to render the data

 <!DOCTYPE html>
 <html>
 <head>
     <title></title>
 	<meta charset="utf-8" />
     
 </head>
 <body>
    <button id="clickMe" >Asynchronous Module Defination</button>
     <script data-main="Scripts/js/config" src="Scripts/js/require.js"></script>
     <script>
         alert('before required keyword')
         require(['config'], function () {
             require(['CustomScript/jQueryFile']);
         });
     </script>
 </body>
 </html>
 

Now build the application and browse RequireJSTest.html page

Before requirejs to load the config file

clip_image004

Click on Ok, it will go to load ‘config’ and ‘CustomScript/jQueryFile’. Within the ‘CustomScript/jQueryFile we have the reference of method.js. So, it was loaded.

But we can observe that ‘CustomScript/CusScript’ has not been loaded. Click on the “Asynchronous Module Definition” button will call require([‘CustomScript/CusScript’]); to load ‘CustomScript/CusScript’

clip_image005

So, let’s click on the button, it will give you an alert. Click on OK, will load ‘CustomScript/CusScript’. As ‘CustomScript/CusScript’ has the reference of ‘mootools’, so it will also be loaded asynchronously.

clip_image007

Now let’s enable the dependency, considering “mootools” is having the dependency on “angular”. So, change the config.js file

 requirejs.config({
     
     baseUrl: 'Scripts/js',
     paths: {
         angular: 'angular.min',
         jquery: 'jquery-3.0.0.min',
         mootools: 'mootools-core-1.4.5-full-nocompat',
         methods: 'CustomScript/method'
     }
     ,shim: {
             "angular": { deps: ["mootools"] }
     }
 })
 

Now run the application again, we can see before clicking on “Asynchronous Module Definition” button mootools js has been loaded. As “mootools” has the dependency on “angular”, mootools” will be loaded first than “angular”. We can check the order of script in below snapshot.

clip_image009

Hope, this article help you to have some basic ideas on RequireJS and its implementation. In next article we will see how RequireJS can be used for Module Optimization.

Happy Coding

Tarun Kumar Chatterjee

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

Leave a comment