How To Add JS File in Frontend for All Pages in Magento 2

Any tricks or shortcuts that ease the Magento 2 admin’s tasks are always welcome!

I am always looking out for such tricks to add to my collection and here’s one such that I’d share with my readers, the method to add JS file in frontend for all pages in Magento 2.

I used this method to implement a Whatsapp contact button on all pages of a Magento 2 store at once without having to place its xml file on each and every page. Thus saving my time!

The below solution can be helpful when you want to implement similar functionality with the JS file on all pages of the store. For example, you want the live support chatbox on all pages. You implemented it on the product page and want it on every store page so that any visitor on any landing page can have access to your live support!

Other examples are popups or notification bar implemented with JS can be displayed on all pages with the below method.

Method to Add JS File in Frontend for All Pages in Magento 2:

  1. Create default.xml at app\code\[Vendor]\[Module]\view\frontend\layout\default.xml
  2. Create or place the JS file at app\code\[Vendor]\[Module]\view\frontend\web\js\js_fileName.js
  3. Run setup upgrade and setup:static-content:deploy command

Quite helpful, isn’t it?

I know! 😄

The steps are easy enough. Still, if you have any doubts, do mention them in the Comments section below and I’d be happy to help.

Do share this useful trick with your social connections!


(based on 17 Reviews)
How To Add JS File in Frontend for All Pages in Magento 2Author Magento Badge

Sanjay Jethva

Sanjay is a co-founder at Meetanshi. He is a Certified Magento Developer who loves creating Magento E-commerce solutions. Owing to his contributions in Magento Forums and posting solutions, he is among the top 50 contributors of the Magento community in 2019. When he is not engrossed with anything related to Magento, he loves to play cricket.

Leave a Reply

Your email address will not be published.