Learn How to Configure Require JS
Magento 2, Require JSRequireJs is basically a JavaScript for the specific module. RequireJs use AMD Standards. RequireJs don’t allow to run global JavaScript. If you have to use JavaScript then add into RequireJS configuration file. RequireJs share code and data between modules and programs. RequireJs load JavaScript into the background so page load speed decreases and this in result boost up the web solution performance.
AMD (Asynchronous Module Definition) is the specification of the JavaScript. It is used to define the module and its dependencies. When it is needful it loads.
Benefits of AMD :
- Used to improve website performance because it loads JavaScript when it is required
- AMD allows developer to define dependencies.
RequireJs in Magento2
Magento 2 is module based web development and it loads the module when it requires. Magento2 adds RequireJs library by default.
Magento 2 by default set baseUrl configuration in requireJs so we do not have to add baseUrl in over custom RequireJs configuration. BaseUrl is one type of prefix of webUrl of the module. In short, it adds baseUrl in the prefix of your module Url. When you see page source of any Magento 2 webpage, you can see the default set baseUrl configuration.
With this configuration, JavaScript file URL look like this
When we have to add JavaScript to the module, we have to add RequireJs module definition to the following path -app/code/Package/Module/view/Area/web/jsfile.js
It is automatically available as RequireJs module name.
Package_Module/jsfile
It can also be loaded via following Url
http://magento2.com/pub/static/adminhtml/Magento/backend/en_US/Package_Module/jsfile.js
It is not required to add .js extension while we add JavaScript file in RequireJs module.
There are main two types of area available in magento2
- Front-end – only accessible to front side
- AdminHTML – only accessible to admin side
- Base – it allow to access both side (front-end/AdminHTML)
If you want to write your RequireJs code into phtml file, start writing immediately using following code:
<script type="text/javascript"> requirejs('Package_Module/jsfile', function(jsfile){ //...program here... }); </script> |
eg..
<script type="text/javascript"> requirejs('MyCompany_Js/js/sample', function(){ alert('Hello World'); }); </script> |
It gives alert when your page is load.
Configure RequireJS
Magento 2 has modular architecture so we have to define RequireJS configuration file for each module and separately to each area (frontend/adminhtml).
Following are the location where requirejs-config.js are stored.
- For modules: <Module_dir>/view/<area>/requirejs-config.js
- For Themes : <theme_dir>/requirejs-config.js
This is a special RequireJS configuration file that magento automatically loads on every webpage.
Add app/code/Package/Module/view/base/requirejs-config.js in your custom module and add your code.
eg. alert(‘Testing’);
Clear cache and reload any page it will give alert.
This is special file that magento generate during when you run following command :
setup:di:compile <strong>or</strong> setup:static-content:deploy |
If you look requirejs-config.js source file on browser, it’s looks following code
This is not completely requireJs code. Magento 2 adds some additional code.
Magento 2 allow us to add some additional configuration in the system
var config = { paths:{ "my_module":"Package_Module/my_module" } }; |
Paths attribute allow to create alias of requireJs definition file path.
RequireJs provide features like Paths, shim, deps, baseUrl etc…
Understanding Lazy Loading
Another important thing is that RequireJS module is lazy loading. It short, RequireJS will not load any JavaScript until it requires.
ex.
var config = { paths:{ "my_module":"Package_Module/my_module" } }; requirejs(['my_module'], function(my_module){ // Your Code }); |
OR
requirejs(['Package_Module/my_module'], function(my_module){ //Your Code }); |
In first example we use alias of JavaScript file and in second, we use file path.
JavaScript files are loaded when it required. it means, it saves the bandwidth to download page source file that not needed.
jQuery Object
If you write your plain jquery code in magento 2, it will not allow. We still needs requirejs library to use plain jquery.
In magento 2, jquery loads as RequireJs Module.
<script type="text/javascript"> jQuery(function(){ //your code here }); </script> |
Browser gives warning that jQuery is undefined because Magento 2 only use RequireJS module so we need to add jQuery code as requireJs module.
requirejs(['jquery'], function(jQuery){ jQuery(function(){ //your jquery code here }); }); |
In here, [‘jquery’] is the dependency. Jquery must loaded first before we proceed.
requirejs(['jquery'], function(jQuery){ //Write code here }); |
function(jQuery){} that acts as your programs’ main entry point.
We use many jQuery plugins in our system but it’s not module based. Plugin developer create their plugin by modifying the global jQuery object because it is easy and faster way to create plugins.
Magento 2 does not allow global jQuery. For that it is require to add jQuery plugin via RequireJS.
var config = { paths:{ "jquery.slider":"Package_Module/js/jquery.slider.min" } }; |
The above configuration we create for jQuery slider module that point to the jquery.slider.min.js file in the Package_module module.
Now we can start using jQuery plugin.
requirejs(['jquery','jquery.slider'], function(jQuery, jQuerySlider){ //my code here }); |
Here we add the jQuery as the dependency. When slider plugin use, magento2 load jQuery module first and after load slider module. But sometimes due to network problem, jQuery module load after jquery.slider plugin. RequireJs provide shim configuration that solve this kind of problem.
var config = { paths:{ "jquery.cookie":"Package_Module/path/to/jquery.slider.min" }, shim:{ 'jquery.slider':{ 'deps':['jquery'] } } }; |
Here we use shim configuration. It accept key value pair, key is the path of plugin or alias of the plugin path. deps is define the dependency on the module.
In this example we add jQuery dependency in slider module. It means, it first loads jQuery entirely and after load slider module.
Let’s take one example to better understand the RequireJs.
eg.
Create a module MyCompany_Js and add requirejs-config.js file in app/code/MyCompany/Js/view/frontend/requirejs-config.js and write configuration in it.
var config = { paths:{ customjs:'MyCompany_Js/js/sample' }, "shim":{ 'customjs':{ deps:['jquery'] } } }; |
Here we added MyCompany_Js/js/sample.js file and jQuery dependency. In short when MyCompany_Js/js/sample module loads, it first load jQuery and then sample module.
Now add your sample.js file in app/code/MyCompany/Js/view/frontend/web/js/ folder and write your program.
var dynamicTextbox=function(){ return "<li><input type="text" name="options[]" /></li>"; } |
I am creating a one function that return textbox. Now we have to call this function in .phtml file.
<button id='click'>Add Textbox</button> <ul id="textboxGroup"></ul> <script> require([ 'jquery', 'customjs' ],function ($) { $('#click').click(function(){ var newTxtbox= dynamicTextbox(); $('#textboxGroup).append(newTxtbox); }); }); </script> |
When I press the ‘Add Textbox’ button, it will call the entry function of RequireJs module and it loads the jQuery module. After that dynamicTextbox() function will be called which returns the new textbox and append that box.
Tell us about your project
Hire dedicated Magento developer from the vast and talented pool of resources.