How to load custom module js file in magento 2?
Finally, I got the solution for my query. I would like to share it in details as below.
Step 1: Add your module js file under <Vendor>/<Module_Name>/view/<area>/web/js/
e.g. <Vendor>/<Module_Name>/view/<area>/web/js/flexslider.js
Step 2: Create requirejs-config.js
file under <Vendor>/<Module_Name>/view/<area>/
e.g. <Vendor>/<Module_Name>/view/<frontend>/requirejs-config.js
Add following code to requirejs-config.js
var config = {
map: {
'*': {
bannerslider: 'VendorName_ModuleName/js/flexslider'
}
}
};
Note: you may set your object name as per your choice. In my case I have set as bannerslider
and do not add the .js extension to file name in VendorName_ModuleName/js/flexslider
Step 3: Call the function
of your module js in .phtml
file as following manner.
<script type="text/javascript">
require(['jquery','bannerslider'],function($){
$(window).load(function() {
$('.flexslider-8').flexslider({
animation: "fade",
controlNav: "thumbnails",
slideshowSpeed: 2000,
minItems: 2,
maxItems: 4
});
});
});
</script>
Its working fine for me.
Trace : Use Net
tab to see requested URL of js file loaded or not.
My way is:
Step 1
Include an extension's base javascript file using layout instructions.
Step 2
Require the extension's other javascript files from the base file with RequireJS:
require(
[
'jquery',
'{VendorName}_{ModuleName}{path_to_js_file/relative_to/view/web/no_js_at_end}'
// ex. Magento/Ui/view/base/web/js/grid/sticky/sticky.js
// became Magento_Ui/js/grid/sticky/stick
],
function($, someOtherLibrary) {
// custom code here...
);
});