Magento – How to include custom JS files in magento 2 custom module

magento-2.1magento2requirejs

I am well aware of a RequireJS feature of Magento 2. I used it quite well for some JS scripts.

require(['jquery', 'ajaxform', ''], function (jQuery)
{
         // JS code
});

But now I have a template HTML for which I have custom JS files to perform actions.

Like –

<div class="font-dp">
     <div class="">
          <select class="form-control" id="font-dropdown">
          </select>
       </div>
</div>

Now here I am fetching options for above select tag dynamically using JSON from a custom JS file.
I have not used any JS code on the template file. I have called events on each HTML element from custom JS files. I have nearly 15-20 JS files like this.

So I am confused about how to include these JS files in my custom module. I have rendered my template on front-end using the custom module. How should I add JS files?

Best Answer

I found a solution at last. Thanks @mike-smith for reference.

I added something like this in Namespace/Modulename/view/frontend/modulename_index_index.xml

 <head>
    <!--For CSS-->
    <css src="Namespace_Modulename::css/my_custom.css"/>

    <!--and for JS-->
    <link src="Namespace_Modulename::js/my_custom.js"/>
</head>

I added CSS file my_custom.css in Namespace/Modulename/view/frontend/web/css/ folder and JS file my_custom.js in Namespace/Modulename/view/frontend/web/js/ folder.

Related Topic