I'm working on customizing my Magento 2 theme, and I need to add a custom JavaScript file to enhance certain front-end functionalities. I've tried a few methods, including modifying the JS file and placing the JS file in the correct theme directory, but it doesn't seem to be loading. Are there any steps I might be missing, or is there a recommended way to include custom JS files in Magento 2 themes to my client site Apkinstal?
Any insights or guidance would be greatly appreciated!
Hello @hiratareen61d5
Add JS to your theme you have several possibilities.
By utilizing default_head_blocks.xml in app/design/frontend/Vendor/Theme/Magento_Theme/layout/:
<?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="js/sample.js"/> </head> </page>
And Create js file in app/design/frontend/Vendor/Theme/web/js/:
require(['jquery', 'jquery/ui'], function ($) {
"use strict";
$(document).ready(function($){
console.log("JS Called.");
});
});
Hope it helps !
If you find our reply helpful, please give us kudos.
A Leading Magento Development Agency That Delivers Powerful Results, Innovation, and Secure Digital Transformation.
WebDesk Solution Support Team
Get a Free Quote | | Adobe Commerce Partner | Hire Us | Call Us 877.536.3789
Thank You,
WebDesk Solution Support Team
Get a Free Quote | Email | Adobe Commerce Partner | Hire Us | Call Us 877.536.3789
Location: 150 King St. W. Toronto, ON M5H 1J9
Hey,
- add js in head block in your theme layout file <?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="Magento_Theme::js/custom-js.js"/> </head> </page> - using requirejs-config.js var config = { paths: { "customJs": 'Magento_Theme/js/custom-js' } } customJs object can be used to add custom js in any other js file - in phtml file you can use script tag to import js direct or you can add script by following way <script type="text/x-magento-init"> { "*": { "Magento_Theme/js/custom-js": {} // use your custom config data to fetch in javascript file } } </script>