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.
The following are some of the many methods for adding custom JS to Magento 2.
<div class="example-class" data-mage-init='{"customjs": {}}'>Custom div</div>
<script type="text/x-magento-init"> { "*": { "Magento_Custom/js/customjs": { "param1": "Value1", "param2": "Value2" } } } </script>
define(['jquery'], function ($) { 'use strict'; return function(config) { console.log(config); console.log(config.param1); console.log(config.param2); } });
<?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>
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.