Blog

How To Add Custom Javascript In Magento 2

This article is about most demanded topic add custom JS in Magento2. There are many ways to add custom js in Magento 2. Magento 2 uses Require JS lib and Knockout JS lib to solve the page speed and manage the JS dependency. As JS are loaded asynchronously in backend, it helps to increase the page speed.

The JS files can be found in following locations :

 - lib/web/js
 - view/areaname/web/js
 - theme/module/web/js
 - theme/web/js

Magento 2 uses requirejs-config.js in module view/areaname/ folder to map the JS file with alias.

Magento 2 declares JS using following ways :

    • data-mage-init
    • <script type=”text/x-magento-init”> ……….. </script>
    • <script> only widgets with requireJS </script> 

The following are the different ways to add custom JS in Magento2:

    • Method 1- data-mage-init attribute
    • Method 2-Adding Layout
    • Method 3 – <script type=”text/x-magento-init”>

Lets start with the method 1:-

Method 1- data-mage-init attribute

This approach uses a unique data-mage-init attribute which allow using JS modularly as well as background and asynchronous loading.

The attribute must contain

      • the JS module path as a value,
      • the element to which we want to apply our JS code to and
      • configuration parameters.

Example: add your custom javascript file and add your code in it.

app/code/Thecoachsmb/Demo/view/frontend/web/js/customjs.js

app/code/Thecoachsmb/Demo/view/frontend/requirejs-config.js

Sometimes we have to pass more than one argument to our module. The syntax of data-mage-init attribute can be difficult to read, so type=”text/x-magento-init” can be used as an alternative. It looks like this:

<script type="text/x-magento-init">
    {
        "*": {
            "Thecoachsmb_Demo/js/customjs": {
                "param1": "Value1",
                "param2": "Value2"
            }
        }
    }
</script>

And you can access this value into your custom javascript file like below:

define([
    'jquery',
    'domReady',
], function ($,dom) {
    'use strict';
    return function(config) {
        console.log(config);
        console.log(config.param1);
        console.log(config.param2);
    }
});

Method 3 -Adding Js with Layout file

This method is least recommended as compared to method 1 and method 2. In this Method you don’t need to define your custom javascript to requirejs-config.js file. Simply add your custom js file to layout using <script> tag.

In app/code/Thecoachsmb/Demo/view/frontend/layout/default_head_blocks.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
         <script src="Thecoachsmb_RequireJsDemo::js/customjs.js" />
    </head>
</page>



	

Leave a Reply

Your email address will not be published. Required fields are marked *

🚀 Let’s Connect on LinkedIn! 🚀

Want to level up your skills and knowledge? 🚀
Follow us on LinkedIn to get:
✅ Expert insights on business growth
✅ Daily tips to sharpen your skills
✅ Exclusive updates from The Coach SMB

Let's grow together!