Getting Started with Require-JS -Part 1

Hi Friends,

In this section, we are going to look at one of the main parts of JavaScript components and that is RequireJS. In order to write enterprise level app, where in you end up writing tons of javascript, its really important to stick to Modularity. Every module and component should have its own meaning; its pretty much like “Single Responsibility Principle“. This way we can manage consistency, dependency across app. Everybody likes neat and clean code but very few follows the principle. I believe, it should be part of our DNA to write clean and maintainable code so that others can understand.


Below is just the glimpse of basic Movies collection. This is basic HTML page which is doing CRUD operation kind of stuff. Although, this not backed by any back-end database, although local-storage is used here.


Now, when you add new movie button, it will come like shown below.


Here, you can add multiple movies as well! Delete Movies will delete all the movies from the collection.


Now, this was all about HTML stuff. Now, let’s look code behind the same. Below is the simple HTML, CSS and JS file.


And JS file.

If you look at the JS file currently, its very complicated. Everything is here itself, which will in future cause problem while maintaining the stuffs as this file will keep becoming bulky and bulky as and when more functionalities will get added here. In order to fix this kind of scenario, Dependency Management in form of RequireJS comes for rescue.

To use RequireJS in our app, we first need to download the same from the site Once, we have downloaded the same, then we need to put the same in our app like shown below.


Now, we need to refer the same in our app like shown below.


Here, I have done couple of things like, I have renamed movies.js to main.js just to make sure this is the first script from app which needs to bootstrap the app. After that, instead of referring to main.js directly and then, I have used data-main attribute. data-main is the entry point of our application. RequireJS will use this attribute to look for main component of the app. With that change in place, now when I go ahead and refresh the page, then it will produce the same exact result like shown below.


However, when I look at the network tab, I see below stuffs.


Here, 1st RequireJS gets loaded then main.js gets loaded. Also, in the initiator column which is the fourth column you can see that main.js is loaded by require.js. I hope you would have liked this discussion. In coming sections, we will delve further inside.

Rahul Sahay
Happy Coding

2 thoughts on “Getting Started with Require-JS -Part 1

  1. Good one, but still you have not discussed the advantage of requireJs over regular way of writing Js scripts.

Comments are closed.