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!

#javascript #magento #magento2 #requirejs

5 views0 comments

Recent Posts

See All

Magento 2 CMS block with the same ID already exists

I have seen the below error when I open cms block grid something went wrong with processing the default view and we have restored the filter to its original state. I found the below log in the excepti

How to generate bearer token - Magento 2 REST API

We can generate the admin bearer token using the below command. Please run the below command in the terminal to generate a token. curl -XPOST -H 'Content-Type: application/json' http://www.domain.com/

Magento 2 script tag and available options in layout xml

We can add a script via layout XML file in Magento 2. The below format will stop the HTML parse until js downloaded and executed. <script src="Bilal_Usean/js/sample.min.js" /> The below format will st

Follow Me

  • LinkedIn
  • Twitter
  • Facebook
  • YouTube
  • Instagram

©2020 by Bilal Usean. Proudly created with Wix.com