Magento – How to add custom js file in Magento 2 in custom theme without use module

customjavascriptmagento2

I used custom theme in magento 2. I want to add custom js file for navigation in magento 2 but js file not work.

I add js link in default_head_block.xml but a js doesn't work.

<link src="js/menu.js"/> 

Best Answer

create the file /app/design/frontend/Vendor/customtheme/Magento_Theme/layout/default_head_blocks.xml

assume you are trying to add bootstrap.js

File : default_head_blocks.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
         <!--Include js From CDN-->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" src_type="url" />
         <!--Include js From Custom module app/code/Company/Module/view/frontend/web/js-->
        <script src="Company_Module::js/bootstrap.min.js"/>        
    </head>
</page>

Please remove static files and flush magento cache

Related Topic