Javascript loading using RequireJs
Javascript loading using RequireJS
RequireJS is a JavaScript file and module loader. It’s used to manage js files and internal/external plugin dependencies and also to optimize Javascript loading
The post describes how to setting up a simple project that use some RequireJs features.
Setting up the project
The following image shows the project setup:
- scripts: contains the main.js file and some modules that we will include in our main page.
- scripts/external: contains require.js file, and HammerJs. We will include HammerJs as module dependency.
- index.html: includes the core of require.js;
Include RequireJS in project
Firstly, we need to include RequireJS in our index.html page:
The data-main attribute is used to specify the main module used by RequireJS.
Define the main module
The main.js contains the main module that will group and execute all project modules, it also define some configurations by using the require.config object, for example: paths of dependencies or the baseUrl.
Define modules
The common function that is used to declare modules is define:
define([module_name], [dependencies_array], [callback_function])
The following code shows the modules that are part of our project:
The modules-two.js also declares one dependency of HammerJs by using the [dependencies_array].
r.js Optimizer
r.js is a RequireJs adapter. It offers some optimization tools, for example: scripts merger and scripts minimizer. r.js can be run using different platforms: Node, Java or browser; r.js can be downloaded here.
Adding r.js to our project
First of all, You need to create a new folder named “optimizer” inside the project and download r.js inside it.
After that, you need to add the r.js config file: build.config.js.
build.config.js declares all build configurations and the output path that will contain all modules merged and minimified into an unique file.
Launching the optimization
The command that starts the optimization of project is:
node < path_r_js_file > -o < path_build_config_file >
For example:
You will find the result of optimization inside the file: built\main-build.js.
Conclusion
Source code of demo project is available on GitHub.
You can find more information about RequireJs on the official website