Four Ways to Add JavaScript to Magento 2

Dec 4, 2018371Vladimir Khrebtov
Four Ways to Add JavaScript to Magento 2

In this article we will take a look at connecting JavaScript in Magento 2. I would like to study with you four ways of connecting:

Via <script type=”text/javascript></script>
In Magento style
Imperative approach
Via require-config.js file

Via <script type=”text/javascript></script>

This is the easiest, but unreliable way, which one and only one advantage is simplicity. Reserving to this method can be justified if you want to connect third-party libraries. In other cases, this approach has several significant drawbacks: the code will be difficult to use again and it can block the page loading (of course, it depends on what the script contains). It is obvious that as the complexity of the project increases, it becomes very difficult to control such code. When discussing this method we should also mention CSP (Content-Security-Policy). The code connected in this way is very vulnerable to CSS attacks (Cross-site scripting). If you still want to use this method, then add the following attributes when connecting: deferred=”true”, async=”true”.

In Magento style

Now let’s consider the ways to connect JS scripts in Magento style. First of all, it’s worth mentioning that Magento 2 uses RequireJS scripts to connect JS. This approach allows to use JS modularly, as well as background and asynchronous loading. To learn more, follow the link to requirejs.org.

So, the first way is to use the special data-mage-init attribute . The attribute must contain the path to the JS module as a value, the element which we want to apply our JS code to and configuration parameters.

For example, imagine that we have a requireJS module that calls a popup window. Let’s create a JS file in the following directory:

app/code/Example/JavascriptInitExample/view/frontend/web/example.js

Next, we will write the following code inside the file:

Now imagine that there is a certain template in which we want to connect our JS module. For starters, let’s connect it the following way:

When loading a page, the browser will simply show a pop-up window with the specified text. Nothing special, but what if we pass some configuration values to data-mage-init? For example, let’s write this:

And change the JS module in the following way:

When the page is reloaded, we will get the same pop-up window, but if we take a look at the console, we will see that the value of the config parameter equals the value. Similarly, we can pass any parameters inside our JS module. In addition to that, we can pass a DOM element as a parameter, on which we call our script. To do this, we rewrite our module the following way:

When the page is reloaded, the output of the element will be added to the console. In our case, this will be

We can also come across a situation, when we pass a series of arguments to our block using the <arguments></arguments> tag in the layout. If we want to get these arguments as parameters for our JS module, then we need to pass them in the following way:

We get JSON as an input parameter, which we can further use at our discretion.

Often we have to pass more than one argument to our module. The syntax that was described above can be difficult to read, so type=”text/x-magento-init” can be used as an alternative. It looks like this:

As you can see, this code is much easier to read.

The imperative approach

It is also worth mentioning the so-called imperative approach in connecting JS modules, which can often be found in the Magento 2 code. However, it is recommended in M2 documentation not to use it. Here is what the connection looks like:

Via require-config.js file

And finally, let’s consider the case when we need to connect the script not at the same page and in a specific element, but on multiple pages at once. In this case, you can use the require-config.js file, which needs to be created in the module folder in the view/base/require-config.js sub-directory. The content should look like this:

In this case, the scripts we have connected will work on all pages of the module. Usually, some third-party libraries are connected in this way. You can also set the map property and define the prefixes for various modules. In future, we can use these prefixes to connect the required JS modules in other modules. For example:

Now we can use the created alias to connect the corresponding JS module:

If you need to determine the loading order of JS files, you can use the shim option.

So, you’ve learned about every method of adding JS to Magento 2. Yet it’s a common knowledge that it increases page loading time, which can reflect negatively on your webstore. What can you do in this case? I would strongly recommend to you Defer JS for Magento 2 module which moves JavaScript to the bottom of the page and speeds up loading. With this module you’ll kill two birds with one stone – install JavaScript and won’t harm your webstore.

So, these were all the existing ways to connect JS files in Magento 2, hope everything was clear. Thank you for reading, please leave your comments and questions in the section below.



Post a new comment

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