Adding Static JavaScript Code Across All Magento Pages
Hello developers! Today I’m going to guide you through adding static JavaScript code across all pages of your Magento site, specifically in the footer section.
Understanding the Requirement
You want to initialize some JavaScript functionality and include an external JS file on every single page of your Magento store. You’ve landed at the right place!
The Plan: Using the Footer Block for Global Scripts
The best way to achieve this is by utilizing the footer block that comes with every Magento theme. This block allows you to add scripts that should be loaded on every page.
Step-by-Step Guide
1. Create a New XML File
Navigate to your theme directory under app/design/frontend/<vendor>/<theme>. Next, create a new file named footer_links.phtml in the /template/html folder of your current theme.
mkdir -p app/design/frontend/<vendor>/<theme>/template/html
nano app/design/frontend/<vendor>/<theme>/template/html/footer_links.phtml
2. Add Your JavaScript Initialization
Open the newly created footer_links.phtml file and paste your static JavaScript code inside <script> tags.
<script type="text/javascript">
// Paste your JavaScript initialization here, for example:
var myApp = new MyApplication();
console.log('Initializing app...');
</script>
3. Include the External JS File
To include an external JS file, you can use Magento’s skin/js directory. First, upload your file to this location.
mkdir -p pub/skin/frontend/<vendor>/<theme>/js/
Then, in your footer_links.phtml, add a script tag to load the external file:
<script type="text/javascript" src="{{view file='Magento_Theme::js/my-external-script.js'}}"></script>
4. Reference the New Footer Block
Now, you need to tell Magento to use the footer_links.phtml file in the footer.
Open your theme’s app/design/frontend/<vendor>/<theme>/layout/default.xml file and add the following code inside the <default> tag:
<referenceContainer name="after.body.end">
<block class="Magento\Framework\View\Element\Template" template="html/footer_links.phtml"/>
</referenceContainer>
Save all your changes.
Testing Your Setup
To test if everything is working, navigate to any page on your Magento site. Right-click and inspect the element, then go to the Sources tab. You should see your JavaScript files loaded in the <head> section or just before the closing </body> tag.
That’s it! Now every single page of your Magento store will load your static JavaScript code as you specified.
Conclusion
Adding global scripts in Magento is a common requirement, and I hope this guide has provided you with an easy-to-follow solution. Remember to always keep your themes and core files up-to-date to ensure compatibility with future updates.
For more advanced customizations or if you’re looking for professional development services, feel free to reach out to us at Laravel Company, where our experienced team can help you optimize your Magento store’s performance.