How to add custom js file from phtml

Do you want to move your phtml script jquery code in js file, then you can proceed with blow steps. Benefits-: If you added your custom JQuery code in js file instead of in phtml. It will reduce your page size.

Step 1. Remove your JQuery code from phtml and create a js file in web/js/, You can create that file in the theme or module.

Copy
                            
define(['jquery'], function($) { 'use strict'; // Put here your js code which you want to move from phtml });

Step 2. Include your JS file from your PHTML. Add the below code in your PHTML file.

Copy
                            
<script type="text/x-magento-init"> { "*": {"Vendor_Module/js/custom-file": {} }} </script>
2025-05-14 11:57:47
Copyright © 2013-present Magento, Inc. All rights reserved.