Get Free Audit

Utilizing JavaScript Component in Magento 2

Aug 14, 2018

16912 Andrey Litvin

Utilizing JavaScript Component in Magento 2

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:


Now when loading the page you will see an alert with “Hello world”!

Let’s connect jquery and mage/cookies:


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:


In this case, the path to the file is:

Vendor/Module/view/frontend/web/js/myfile.js

Which contains your code:

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:


2) Using a tag with the <script type=”text/x-magento-init” attribute. For example:

Tatiana Buchkova
Partner With Us Let's discuss how to grow your business. Get a Free Quote.
Talk to Tatiana


In these cases the path to the file is:

Vendor/Module/view/frontend/web/js/jsfilename.js

Which contains your 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


2) Using a tag with the <script type=”text/x-magento-init” attribute. For example:


magento development services

Magento Development Service

Take your online store to the next level with BelVG Magento development

Click to visit the page

Initializing 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


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.

Tatiana Buchkova
Partner With Us Looking for a partner to grow your business? We are the right company to bring your webstore to success. Talk to Tatiana

2 Comments

  1. 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

  2. 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.

Post a new comment

BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *