How can I enable and use a custom JavaScript file in Magento 2?

I have a theme.js file located at app/design/frontend/<Vendor>/<theme>/web/js and it depends on jQuery. Now I know there are two possible methods for inclusion, via the recommend RequireJS method or directly from within default_head_blocks.xml.

Now, I believe best practice would be to use RequireJS, but I am unfamiliar with this tool and I'm struggling a bit being able to get my theme.js included. Could someone point me in the right direction, please? I've read the documentation, but I'm still unable to grasp the concept properly at this stage and I cannot get it to work.

  • 1
    Please review following URL, you will get more idea about. magento.stackexchange.com/questions/85851/… Feb 23, 2016 at 12:00
  • Still, confused. I'm not able to include external JS resources. Just can't figure it out. Feb 23, 2016 at 14:01
  • You had post your answer as below : I've figured it out, so please see my answer at Magento 2: requirejs-config.js in themes? So please recheck once again. If it is not working kindly update it or delete it. Feb 24, 2016 at 8:56
  • That was posted after I made the comment above. Feb 24, 2016 at 10:42

2 Answers 2


Lets define some points about Magento's JavaScript:

  • There is possibility to place JS inline (in <script /> tags) and I don't recommend to practice so.
  • So your code should be located in separate file. And you are asking how to include it on the page. Solutions:

    1. Via block mechanism place a phtml template and place there a declarative invoker (as mentioned @Gareth).
    2. Custom script can be loaded via RequireJS config. But script will be loaded on every page for particular area. If you ok with this than:

      app/design/frontend/<Vendor>/<theme>/requirejs-config.js with

      var config = { "deps": "js/theme" };

      , where js/theme is path to real file app/design/frontend/<Vendor>/<theme>/web/js/theme.js.


I've figured it out, so please see my answer at Magento 2: requirejs-config.js in themes?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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