Requirejs Magento 2

In this article, we will take a tour about how to use requirejs in Magento 2 with simple examples.

What is requirejs?

In Magento 2, almost all the javascript files are loaded by requirejs concept (lazy load).

For example below snippet first load jquery then execute your code.

requirejs(['jquery'], function(jQuery){

// Your code here

});

Prerequisite for follow this tutorial [optional]

I already created a boilerplate module, which makes easy to follow this tutorial. It is optional, you can follow with your own module too.

  1. Download module repository from bitbucket
  2. Extract downloaded folder
  3. Copy Bilal folder into your <magento-root>/app/code/

After run the below commands to enable module

$ php bin/magento module:enable Bilal_RequirejsAlert
$ php bin/magento setup:upgrade

Once you’ve run the above, you should be able to access the following URL in your system

http://your-host/require/alert

and see the rendered text

Hello alert/index.phtml

How to load custom Js via requirejs?

Step 1 : Create your custom js

Bilal/RequirejsAlert/view/frontend/web/js/one.js

define([],function(){
       
 return "return from one";

});

Step 2 : Call created js in needed template file using requirejs 

Bilal/RequirejsAlert/view/frontend/templates/alert/index.phtml

<script type="text/javascript">
requirejs(['Bilal_RequirejsAlert/js/one'], function(msgone){
    alert(msgone);
});
</script>

Clear the cache of magento and browser you can see alert

How to naming the requirejs module?

requirejs([‘Bilal_RequirejsAlert/js/one’]…… This means you could place a RequireJS module definition file in your module at Bilal/RequirejsAlert/view/frontend/web/js/one.js.

Vendor_Module = Vendor/Module/view/frontend/web/

(so)

Vendor_Module/js/one =Vendor/Module/view/frontend/web/js/one.js

I hope it helps!

 

 

 

 

About Bilal

I'm a software programmer, I handle Magento2 modifications at any level.

View all posts by Bilal →

Leave a Reply

Your email address will not be published. Required fields are marked *