How to add a custom JS file in the Magento 2?
You can add a custom JS file to your theme by using the below steps:
1. You need to create a custom JS file on this path: “app/design/frontend/your-theme/web/js/custom.js” and your JS code.
2. You need to call your JS in this file “default_headblock.xml” that file is present on this path: “app/design/frontend/Your Theme/Magento_Theme/layout/default_headblock.xml“ and then you call your JS file here by using the below code.
<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/custom.js"/> </head> </page>
Run cache flush and cache clear command in the Magento root directory.
4. See changes on the front end.
If you get any trouble, please leave your queries in the comment box.
Thank you! have a great day.