cancel
Showing results for 
Search instead for 
Did you mean: 

Adjusting .js file to magento2

Adjusting .js file to magento2

hi everyone, I've a couple of questions and need help with them.

Where should I place a JavaScript file to ensure it's accessible across all pages globally?

Secondly, let's assume there's a module named "module-layered-navigation," and I intend to override it within my theme (free iphone) while adding a JavaScript file exclusively for this module. How can I accomplish this while ensuring that the JavaScript file remains confined to this specific module?

1 REPLY 1

Re: Adjusting .js file to magento2

To make a custom JavaScript file globally available across all pages in Magento 2, the ideal location to place the JS file is:

app/design/frontend/[Vendor]/[Theme]/Magento_Theme/layout

Within that theme-level layout directory, create a new .XML file (e.g. myscript.xml) with the following contents to load your JS file:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<script src="js/myscript.js"/>
</head>
</page>

This will automatically add a reference to myscript.js file inside the <head> of every page.

Then inside the same theme folder structure, place your actual myscript.js file at:

app/design/frontend/[Vendor]/[Theme]/Magento_Theme/web/js/myscript.js

This complete setup will globally import your JS functionality throughout all frontend store pages.