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.
Leave a Comment
(1 Comment)
Does the name of function, the alias, and file name should be same…?
Can you please add an example with multiple functions in custom.js and ways to call them from phtml file in fronend/adminhtml custom theme…?
Also how can we use Ajax URL in custom.js that we can have in its phtml?
PLease guide
Useful Magento 2 Articles
Author Info
Chirag
Connect With Me