What is x-magento-init?

31 Dec 2018
Blog image

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.

Was this article helpful?
Jayanka Ghosh

Jayanka Ghosh

Experienced Magento Developer with a proven track record in the IT and services industry, specializing in PHP, Magento, HTML, jQuery, CSS, and E-commerce.

Our Offices Are Here

India flag

India

7th Floor, Jupiter Block Prestige Tech Park, Kadubeesanahalli, Bellandur Amtankere, Bengaluru, Karnataka 560103

+91 888 49 00 505

UAE flag

UAE

DTECH, Techno Hub 1, Dubai Silicon Oasis Authority, United Arab Emirates - Dubai - United Arab Emirates

+971 55 557 8583

Saudi Arabia flag

Saudi Arabia

Building No 6827, Prince Turki Ibn Abdulaziz Al Awal Street, Al Muhammadiyah District, Riyadh, Kingdom of Saudi Arabia- 12362

+966 50 809 6356

Oman flag

Oman

Building No. 2/786, Way No. 43, Block No. 336, Al Khud 132, Muscat, Oman

+968 7694 6200

Singapore flag

Singapore

Codilar Digital Pte Ltd, 68 Circular Road, #02-01, 049422, Singapore

Indonesia flag

Indonesia

Satrio Tower, Floor 6, Unit C and D, Desa/Kelurahan Kuningan Timur, Kec. Setiabudi, Kota Adm. Jakarta Selatan, Provinsi DKI Jakarta

CONTACT US

Let's Do Something Great Together

We look forward to hearing from you

REGIONS

KSA|UAE|OMAN|INDIA|SINGAPORE|INDONESIA