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"/> 

Goto your default.xml to the below location:


And add the below code:

<?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">
        <script src="Magento_Theme::js/custom.js"/>

Now place your custom.js under below location:


Now you can add your to the js file as you want.

  • <?xml version="1.0"?> <page xmlns:xsi="w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> <script src="Magento_Theme::js/menu.js"/> </head> </page> Add js file but js file not loaded – Gagan Dec 6 '18 at 9:50
  • Did you flush the cache? Also you need to run static-content:deploy as well. – Sukumar Gorai Dec 6 '18 at 10:09

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">
         <!--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"/>        

Please remove static files and flush magento cache


The best way to add a JS in Magento (theme or module) is with REQUIREJS.

To add a js in theme via Requirejs:

Supposing that your js file is: myfile.js


var config = {
    map: {
        '*': {
            myscript: 'js/myfile'


define(['jquery'], function($){
   "use strict";
       return function myscript()
           alert('hello myscript');
           //put all your myfile js code here


<script type="text/javascript">
    require(['jquery', 'myscript'], function($, myscript) {

Info: don't forget to :

  • clean the cache

  • clean var/view_preprocessed content

  • clean pub/static content

  • deploy the static content = php bin/magento setup:static-content:deploy -f

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.