Magento 2 uses the RequireJS library to work with JavaScript. The library uses an asynchronous dependency loading model — AMD. This allows you to optimize the time it takes to load a page, containing JavaScript files. Also, by managing the JavaScript resources dependencies, we get rid of the duplication of the loaded libraries.
Places where JavaScript resources are stored
JavaScript component
Define vs require
Insert a JS component in a PHTML template
Initializing a component on a selector
Initializing a component on a selector with parameter
Initializing a component on a selector in JavaScript
Places where JavaScript resources are stored
- lib/web/ — this folder contains the libraries that are used in Magento. These could be either third-party libraries such as jquery, underscore.js, knockout.js, or the Magento ones based on them in the /mage/folder;
- app/code/[Vendor]/[Module]/view/[areaName]/web/ — a path for javascript files used in the module;
- app/design/[areaName]/[VendorTheme]/[themeName]/web/ — a path for javascript files used in the theme;
- app/design/[areaName]/[VendorTheme]/[themeName]/[Vendor]_[Module]/web/ — a path for inheritance javascript files of the module.
JavaScript component
JS component is a RequireJS module decorated as an AMD module. This approach allows us to encapsulate the logic in modules without clogging the global namespace. Modules can also use other modules.
Here is an example of a simple RequireJS module:
1 2 3 |
requirejs([], function() { alert("Hello World!"); }); |
Now when loading the page you will see an alert with “Hello world”!
Let’s connect jquery and mage/cookies:
1 2 3 4 5 6 |
define([ "jquery", "mage/cookies" ], function($){ ... }); |
As you can see, you need to specify the necessary modules in the form of an array to connect the modules. Then RequireJs will pass the modules to the function in the order of declaring the modules.
Define vs require
If we want to create a module, on which other parts of the application will depend, we need to use define(). And if our module will only use other modules, then require() is used.
Insert a JS component in a PHTML template
Depending on the task, you can use one of the two options for notation:
- using the data-mage-init attribute
- using the <script type=”text/x-magento-init”/> tag
Let’s figure out what options are available and when they can be used. Let’s say you just need a simple connection of JS files, without specifying parameters or components.
A simple connection of JS in PHTML:
1 2 3 4 5 6 7 |
<script type="text/x-magento-init"> { "*": { "Vendor_Module/js/myfile": {} } } </script> |
In this case, the path to the file is:
Vendor/Module/view/frontend/web/js/myfile.js
Which contains your code:
1 2 3 4 5 |
require([], function(){ "use strict"; //your js goes here }); |
Initializing a component on a selector
There are 2 ways to do it:
1) Initializing the component in the data-mage-init attribute. For example:
1 |
<div id="element-id" data-mage-init='{"Vendor_Module/js/myfile":{}}'></div> |
2) Using a tag with the <script type=”text/x-magento-init” attribute. For example:
1 2 3 4 5 6 7 |
<script type="text/x-magento-init"> { "#element-id": { "Vendor_Module/js/myfile": {} } } </script> |
In these cases the path to the file is:
Vendor/Module/view/frontend/web/js/jsfilename.js
Which contains your code:
1 2 3 4 5 6 7 8 9 |
define(['uiComponent'], function (Component) { 'use strict'; return Component.extend({ initialize: function (config, node) { // some code } }); }); |
Initializing a component on a selector with parameters
When a component is initialized, it is also important to send parameters to it, which are determined mostly dynamically in php.
1) data-mage-init
1 2 |
<div id="element-id" data-mage-init='{"Vendor_Module/js/myfile":{"parameter":"value","status":<?php echo $block->getStatus(); ?> }}'></div> |
2) Using a tag with the <script type=”text/x-magento-init” attribute. For example:
1 2 3 4 5 6 7 8 9 10 |
<script type="text/x-magento-init"> { "#element-id": { "Vendor_Module/js/myfile1": { "parameter":"value", "status":<?php echo $block->getStatus(); ?> } } } </script> |
Magento Development Service
Take your online store to the next level with BelVG Magento development
Click to visit the pageInitializing a component on a selector in JavaScript
If we do not have dynamic parameters obtained with php, we can initialize the component on a selector in a javascript file.
For example:
vendor/magento/module-swatches/view/adminhtml/web/js/visual.js
1 2 3 4 5 6 7 8 9 10 |
… $('[data-role=swatch-visual-options-container]').sortable({ distance: 8, tolerance: 'pointer', cancel: 'input, button', axis: 'y', .... } }); ... |
Please leave your questions in the comment section below, if something remains unclear.
Turn to BelVG ecommerce development company for a full range of Magento development services.
Hi, Hiren! Thanks for your question!
Define is used when you want to use the module several times. I will give you an example.
Let us create 3 JS files.
/app/code/Belvg/JsExample/view/frontend/web/js/object.js:
define([‘jquery’], function($) {
return {
a: 1,
setA: function(value) {
this.a = value;
},
getA: function() {
return this.a;
},
incrementA: function() {
this.setA(this.getA() + 1);
},
};
});
/app/code/Belvg/JsExample/view/frontend/web/js/script1.js:
require([‘Belvg_JsExample/js/object’], function(object) {
console.log(‘script 1. “a” before: ‘ + object.getA());
object.incrementA();
console.log(‘script 1. “a” after: ‘ + object.getA());
});
/app/code/Belvg/JsExample/view/frontend/web/js/script2.js:
require([‘Belvg_JsExample/js/object’], function(object) {
console.log(‘script 2. “a” before: ‘ + object.getA());
object.incrementA();
console.log(‘script 2. “a” after: ‘ + object.getA());
});
As you can see, in 2 different script1 and script2 files the same object.js module is used. Connect the files script1.js and script2.js to the layout
/app/code/Belvg/JsExample/view/frontend/layout/jsexample_index_index.xml:
The result will look the following way:
script 1. “a” before: 1
script 1. “a” after: 2
script 2. “a” before: 2
script 2. “a” after: 3
i really liked your blogs. really helpful to everyone must say. i have bit confusion regarding Define vs require, can you please give a more example , it will really useful for me. Thanks in advance.