I'm curious about a couple of things. Firstly, I'm wondering where I should place a JavaScript file so that it's accessible across all pages of my website. Secondly, let's dive into a scenario: Suppose there's a module named "module-layered-navigation," and I'd like to customize it within my apktod 's theme by adding a JavaScript file dedicated to this module. How can I go about this, ensuring that the JavaScript file is limited to use within this specific module?
If you want to load and access your JS file across all the pages, follow the below steps.
1. Place the JS file in the theme directory - <theme_dir>/web/js/
2. Load JS file using default_head_blocks.xml layout at path - <theme_dir>/Magento_Theme/layout/
<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/custom.js" /> </head> </page>
OR
Create requirejs-config.js file in your theme root with the below content.
var config = { deps: [ "js/custom", ] };
To load JS for a specific module
1. Move the JS file to Custom/Module/view/frontend/web/js/
2. Load the JS file using layout Custom/Module/view/frontend/layout/default.xml with the below content.
<head> <script src="Custom_Module::js/custom.js"/> </head>
Please let me know if any further assistance is needed.