How to Call Custom JS File in PHTML in Magento 2

Magento 2 uses an asynchronous approach to load the JAVASCRIPT file in a page. Magento 2 achieve this approach using require JS library. Magento 2 developers often need to call custom JS file in a particular PHTML file.

Developers often makes mistake in call custom JS file in PHTML. Many developers directly add a JS file in the head section. That leads to JS errors in the browser console. Today we will see how to call custom JS file in PHTML the right way.

Call Custom JS File in PHTML in Magento 2

Let’s say you want to add your custom JS in the category page list.phtml file in your theme. To do so, you need to follow the below steps to call a custom JS file in PHTML in Magento 2.

Step 1: Create a JS file custom.js under app/design/frontend/Vendor/Theme/web/js directory.

define([
        "jquery"
    ], function($){
        "use strict";
       return function custom(config, element) {
         alert('My Custom JS');
       }
});

Step 2: Add alias in theme’s requirejs-config.js file under app/design/frontend/Vendor/Theme directory.

var config = {
map: {
        '*': {
            custom: 'js/custom'
        }
    }
};

Step 3: Call custom JS file in PHTML by adding below code in list.phtml file.

<script>
    require(['jquery', 'custom'], function($, custom) {
        custom();
    });
</script>

By adding this code insider your PHTML, you are telling Magento that whenever list.phtml file executed, add custom.js file in the head section.

I hope this post will help you. Feel free to add a comment for any query. If you want to override core JS file insider your theme then please check this post.

Want to ask a question or leave a comment?

Leave a Comment

(0 Comments)

All the comments are goes into moderation before approval. Please do not spam. Your email address will not be published. Required fields are marked *

Enjoy this post? Please support Us!

Follow us on twitter for daily new updates..

 

Want to become
a Magento 2 Expert?

If Yes! Then Subscribe to our newsletter and get weekly article to you email id.
Subscribe Here
SUBSCRIBE NOW
close-link

To Avoid Spam Downloads, We Want Your Email

We will send you download link right
away. Please submit form below.
SEND ME DOWNLOAD LINK
Close