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:
- Create default.xml at app\code\[Vendor]\[Module]\view\frontend\layout\default.xml123456<?xml version="1.0"?><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><head><link src="[Vendor]_[Module]::js/js_fileName.js"/></head></page>
- Create or place the JS file at app\code\[Vendor]\[Module]\view\frontend\web\js\js_fileName.js
- 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!