How To Create and Add Custom Javascript In Magento 2

Written by Prashant Dhaduk

Jun 19, 2023

How To Create and Add Custom Javascript In Magento 2

This article will explain how to add custom Javascript to Magento 2. Let’s find out how you can do it.

There are many ways to add custom JavaScript to Magento 2. Magento 2 uses the Require JS library and the Knockout JS library to improve page speed and manage JS dependencies. Because JS is loaded asynchronously on the backend, it helps boost page speed.

For example, a custom module has to be able to choose an image, crop a picture, display charts, and so on. There are many features that may be developed using Javascript to enhance the Magento 2 admin interface.

How to create your custom JS in Magento 2.

  • First, you create your js file in your theme at app/design/frontend/Vendor/Theme/web/js directory, or if you want to use a module-specific then create a js file into your module directory web folder.

The following are some of the many methods for adding custom JS to Magento 2.

  • Method 1- data-mage-init attribute
  • Method 2- using script tag
  • Method 3- Adding Layout

Method 1- data-mage-init attribute

  • This is used to specify a specific HTML element to target. It is less difficult to develop and is frequently used for jQuery UI widgets. This method can only be applied to the specified HTML tag.
  • We simply call our custom javascript code into the phtml file using the data-mage-init tag.
<div class="example-class" data-mage-init='{"customjs": {}}'>Custom div</div>

Method 2- using script tag

  • Sometimes we need to send more than one parameter to our module. Because the syntax of the data-mage-init attribute can be difficult to read, type=”text/x-magento-init” can be an alternative. It looks like below
<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Custom/js/customjs": {
                "param1": "Value1",
                "param2": "Value2"
            }
        }
    }
</script>
  • After that, you may use the following code to retrieve this value in your custom javascript file.
define(['jquery'], function ($) {
    'use strict';
    return function(config) {
        console.log(config);
        console.log(config.param1);
        console.log(config.param2);
    }
});

Method 3- Adding Js with the Layout file

  • In this Method, You do not need to define your custom javascript in the requirejs-config.js file when using this method. Simply include your custom js file in the layout using the script tag.
  • Create default_head_blocks.xml at app/design/frontend/Vendor/Theme/Magento_Theme/layout/ and add the below code.
<?xml version="1.0"?>
<!--
/**
 * Created By: Dolphin Web Solution Pvt. Ltd.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
         <script src="Module_Theme::js/custom.js" />
    </head>
</page>
  • And then paste the following code into your app/design/frontend/Vendor/Theme/Magento_Theme/web/js/custom.js file.
require(["jquery"],function($){
    alert("My Custom Js Code");
});

That’s it! I hope this technical blog will help you find what you were looking for.

If you have any further questions about the add javascript in Magento 2 or if you need any help from our Magento 2 expert, contact us now for a free consultation.

Bookmark it for your future reference. Do comment below if you have any other Questions.

P.S. Do share this note with your team.

Prashant Dhaduk

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP