How to load JAVASCRIPT In a PHTML template with requirejs VIA X-MAGENTO-INIT?

Magento 2 template supports require JS declaration using X-MAGENTO-INIT. You can define require js with the Magento PHTML template file.

Require js loaded as AMD (Asynchronous module definition) based approach.
Benefit:
Declare JS using text/x-magento-init will be loaded after the page DOM is loaded completely. It will improve the page load time.

We can define the script tag with the type is text/x-magento-init.

Syntax of Declare JS file in Magento template,

<script type="text/x-magento-init">
    {
        "*": {
            "Jesadiya_Blog/js/requirejs-demo" : {}
        }
    }
</script>

Here * inside the script tag means nothing.  * will be valid for the entire page.

Optionally you can also add a CSS selector of the specific DOM if you need specific DOM to cover in the template.

demo.phtml file,

<?php declare(strict_types=1);
/** Demo template file */
?>
<script type="text/x-magento-init">
    {
        "*": {
            "Jesadiya_Blog/js/requirejs-demo" : {}
        }
    }
</script>
<div id="main">Main Content</div>

If you want to define JS for the specific DOM, you can add a CSS selector instead of * in the script body.

<script type="text/x-magento-init">
    {
        "#main": {
            "Jesadiya_Blog/js/requirejs-demo" : {}
        }
    }
</script>

If you define CSS selector, the Define requirejs-demo.js file is valid only for the id with main DOM only. You can also define using the class name, CSS selector.

Now Create requirejs-demo.js file in the module to define our custom JS file.
I hope you have created your Magento custom module, I will define the JS file in my custom module called Jesadiya_Blog.
app/code/Jesadiya/Blog/view/frontend/web/js/requirejs-demo.js

define(function () {
    'use strict';

    return function () {
        //YOUR CUSTOM LOGIC GOES HERE
        console.log('This is the basic example of Loading JS file with require JS');
    }
})

Here we have just created a simple JS file without any argument to the function.

Now once you go to the template page in the frontend, you will see the result of console.log in the console tab once the page is loaded completely.


  • Passing Dependency in Require JS file.
define(['jquery', 'ko'], function ($, ko) {
    'use strict';

    return function () {
        //YOUR CUSTOM LOGIC GOES HERE
    }
})

Always define() method takes the first argument as optional Array. If you declare dependency as the first argument, you need to declare the parameter in the function call.

Here We have passed jquery and ko library as dependency to the function. We have to declare4 parameters based on the sort order in the function method.

We have given $ as an alias for the jquery and ko as alias for the knockout JS.