How to call/add a custom JS file in Magento 2?

For adding the custom JS file please follow the below steps:how-to-call-add-a-custom-js-file-in-magento-2 How to call/add a custom JS file in Magento 2?

1. Go to app / design / frontend / [vendor] / [theme] / Magento_Theme / layout / default_head_blocks.xml
2. add this code within default_head_blocks.xml

    <script src="js/custom.js" />

Like this:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../vendor/magento/framework/Module/etc/module.xsd">
  <head>
      <script src="js/custom.js" />
  </head>
</page>
3. Create a custom.css file on this path

Go to app / design / frontend / [vendor] / [theme] / web / js / custom.js
4. After that run the static content deploy command in SSH

 bin/magento setup:static-content:deploy

Please leave your comment for asking any question or suggestion.

Need Help?