Thursday, August 31, 2017

Javascript Modules - Overview

There are basically two runtimes for Javascript:
1. Client-side: Browser
2. Server-side: NodeJs

Client-Side:
Basically a webpage contains tags which will be parsed by a webbrowser with the help of its various components - HTML Parser, CSS parser and JS Engine etc. How Browser executes Javascript is our area of focus while discussing about Javascript modules.

Consider the following html:



The console of the browser when this page is loades shows the following output:
1
2
3
4
5
...

Means..the browser executes the script tags in a sequential fashion.

Consider another sample showing only the script tags:

Lets see how Browser loads the above html:
Browser, executes script tags in a sequential fashion as explained earlier. And if there are any tags that contain downloadable libraries from CDNs or scripts from Server, it downloads them asynchronously but the execution of the same will be sequential(in the order of encountered).
Meaning...once all the CDN libraries(jquery, bootstrap, backbone etc) are downloaded, the js code in 1.js, 2.js, 3.js will be executed respectively. But, sometimes, to speed up the execution, browser executes the scripts asynchronously.

The disadvantages of the approach:
1. Polluting global namespace:
If boht 1.js, 2.js contain a variable named 'a', a scope-conflict occurs. This is called polluting namespace.
2. Dependency: What if a browser executes scripts asynchronously(parallelly). Imagine executing 2.js while 1.js is still downloading or any other CDNs are downloading. And the problem arises if 2.js contain a jquery or backbone js function which is still loading.


To overcome those issues two approaches are defined:
a) CommonJS: ServerSide..NodeJS..Synchronous
b) Asynchronous Module Definition - AMD - Client side - Require.js - Asynchronous
c) ECMA's standard module spec

RequireJS:
This contains 3 basic building blocks:
1. require : Using this we can tell execution-environment(browser) of all the dependencies(js files) that it needs to load before execuing a piece of code.
2. define : Using this we can instruct browser of all the dependencies that the piece of code needs and register the current file(in which the define statement present) with RequireJS so that it can be used in require statement.
3. configure:  Configure shortnames for accessing various js files in different folders.

No comments:

How J2EE components work together in any Container - Spring or Application Server

In a Spring+Jersey+Hibernate RESTful webapplication, we can spot various J2EE components - JTA, JPA, Java Bean Validation, JSON-B API for B...