Magento 2 add custom js


Innovateme guild, you to step by step to add custom js file.

There is three way to add a custom js file to your Magento 2 website.

First Way

1. In the theme open or create app/design/frontend/[Innovateme]/[Theme]/Magento_Theme/layout/default_head_blocks.xml 

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; xsi:noNamespaceSchemaLocation="../. ./. ./. ./. ./. ./. ./lib/internal/Magento/Framework/View/Layout/etc/page_configu­ration.xsd">

  <head>

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

  </head>

</page>


2. Create custom.js file in the app/design/frontend/[Innovateme]/[Theme]/web/js folder.

3. Clear magento cache.

Second Way

1. In the theme open or create app/design/frontend/[Innovateme]/[Theme]/requirejs-config.js

var config = {
   map: {
       '*': {
           custom: 'js/custom',
       }
   }
};

2. Create custom.js file in the app/design/frontend/[Innovateme]/[Theme]/web/js folder.

3. Clear magento cache.

Third Way

1. In the theme open or create app/design/frontend/[Innovateme]/[Theme]/Magento_Theme/layout/default_head_blocks.xml 

<referenceContainer name="after.body.start">
<block class="Magento\Framework\View\Element\Text" name="jquery.bootstrap">
    <arguments>
        <argument translate="true" name="text" xsi:type="string"><![CDATA[<script type="text/x-magento-init">{"*":{"custom":{}}}</script>]]></argument>
    </arguments>
</block>
</referenceContainer>