In this we will see some advanced features of Require JS and their implementation.
Let's start with various config options. We didn't used config file in the previous article.
What is in main.js?
A call to require() to load all the scripts you need and any initialization you want to do for the page. This example main.js script loads two plugins, jquery.alpha.js and jquery.beta.js (not the names of real plugins, just an example). The plugins should be in the same directory as require-jquery.js:
Our config script will look like the preceding. Every parameter is optional and "baseUrl", "paths" are what we mainly used in this application.
Add the script references as shown below in the Master page:
Now in the path section, we added two different versions of jQuery. Note that we didn't add the ".JS" file extension to the script names.
In the Default page, we just added the following script. Two different versions of jQuery files will be handled in this script. One main advantage is that if we want to move to future versions of jQuery, we will simply change config file alone to upgrade the entire application.
Shim is used to Configure the dependencies and exports for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value. Example:
In this code we mentioned that "PrettyPhoto" is dependent on the "jQuery-1.6.1" version and every time the "jQuery-1.6.1" version is loaded before the "PrettyPhoto" loaded. We will check the order of the script as below.
The Asynchronous Module Definition API specifies a mechanism for defining modules such that the module and its dependencies can be asynchronously loaded. Please check the following URL for more details about module.
Created a simple module as mentioned below, just return some string data. We will notice that this as anonymous function, we didn't mention any names.
Define another module with the name "another-message".
For easy understanding these modules are kept as a separate js file and in the Main.jS (wherever required) we can refer to the modules as shown below:
In this code we are calling the anonymous function module, passing jQuery and the anonymous function as the parameter and obtaining the results as shown below.
We will combine one more module called "another-message" and the module code will be placed in a separate file.
The output will combine the results of both modules and will see the order of the modules also.
Using "Require JS" we will write clean code and resolve the dependence via creating the modules.