What is x-magento-init?

Magento uses x-magento-init in numerous places to invoke a RequireJS module as a program. But, the actual potential of x-magento-init lies in its ability to create Magento Javascript components. Let me explain how.

You might have gone through some of Magento's templates and seen a <script type="text/x-magento-init">tag. But what does it mean?

Let's use an example to explain

<script type="text/x-magento-init">
{
    "[data-role=tocart-form]": {
        "catalogAddToCart": {}
    }
}
</script>

Basically, Magento's frontend app engine searches for all script tags with type text/x-magento-init and uses the contents of it to call out certain jQuery widgets on certain DOM elements. Let's see how that works.

So in the above example, the contents of the script tag is a JSON string.

{
    "[data-role=tocart-form]": {
        "catalogAddToCart": {}
    }
}

If we parse this JSON we see that it contains one element with key [data-role=tocart-form](which denotes the DOM selector) and value as a JSON object, whose value is basically the widgets which are to be initialized on that DOM element.

So the above JSON is converted to

$('[data-role=tocart-form]').catalogAddToCart({}); where catalogAddToCartis the widget being called on the DOM element $('[data-role=tocart-form]')

We can use this handy way of instantiating jQuery widgets on certain DOM elements, to keep our code clean, optimized, and maintainable.

But what are jQuery widgets though, and how to create your own widget?

Click here to understand how jQuery widgets work exactly.