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.

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

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

and see the rendered text

How to load custom Js via requirejs?

Step 1 : Create your custom js

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

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

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

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 *