Close [x]

JavaScript initialization

Edit this page on GitHub

Overview

This topic talks about how to initialize a JavaScript component in the Magento 2 application. It covers initializing JavaScript components in a .phtml template and jQuery widget initialization in a JS script. We strongly recommend that you use the described approaches and do not add inline JavaScript.

Do not add JavaScript inline. Instead use the approaches described further.

Initialize a JS component in a PHTML template

In Magento 2, there are two ways to initialize a JS component in a .phtml template: using the data-mage-init attribute and using the <script> tag. Both ways are described in the following sections.

Initialization using data-mage-init

Use the data-mage-init attribute to initialize a JS component on a certain HTML element. The following code sample is an illustration. Here a JS component is initialized on the <nav/> element:

<nav data-mage-init='{ "<component_name>": {...} }'></nav>

When initialized on a certain element, the script is called only for this particular element. It is not automatically initialized for other elements of this type on the page.

How the JS initialization using data-mage-init is processed

On DOM ready, the data-mage-init attribute is parsed to extract components’ names and configuration to be applied to the element. Depending on the type of the JS component initialized, processing is performed as follows:

  • If an object is returned, the initializer tries to find the <component_name> key. If the corresponding value is a function, the initializer passes the config and element values to this function. For example:
    return {
        '<component_name>': function(config, element) { ... }
    };
    
  • If a function is returned, the initializer passes the config and element values to this function. For example:
    return function(config, element) { ... };
    
  • If neither a function nor an object with the "<component_name>" key are returned, then the initializer tries to search for "<component_name>" in the jQuery prototype. If found, the initializer applies it as $(element).<component_name>(config). For example:
    $.fn.<component_name> = function() { ... };
    return;
    
  • If none of the previous cases is true, the component is executed with no further processing. Such a component does not require either config or element. The recommended way to declare such components is using the <script> tag.

Initialization using <script>

To initialize a JS component on a HTML element without direct access to the element or with no relation to a certain element, use the <script type="text/x-magento-init"> tag. An illustration follows:

<script type="text/x-magento-init">
    // components initialized on the element defined by selector
	"<element_selector>": {
		"<js_component1>": ...,
		"<js_component2>": ...
    },
    // components initialized without binding to an element
    "*": {
        "<js_component3">: ...
    }
</script>

Where:

  • <element_selector> is a selector for the element on which the following JS components are initialized.
  • <js_component1> and <js_component2> are the JS components being initialized on the element with the selector specified as <element_selector>.
  • <js_component3> is the JS component initialized with no binding to an element.

The following is an illustration of widget initialization using <script>. Here the accordion and navigation widgets are initialized on the element with the #main-container selector, and the pageCache script is initialized with no binding to any element.

<script type="text/x-magento-init">
    "#main-container": {
        "navigation": <?php echo $block->getNavigationConfig(); ?>,
        "accordion": <?php echo $block->getNavigationAccordionConfig(); ?>
    },
    "*": {
        "pageCache": <?php echo $block->getPageCacheConfig(); ?>
    }
</script>

Widget initialization in JS

To initialize a widget in JS code, use a notation similar to the following (the accordion widget is initialized on the #main-container element as illustration):

$("#main-container").accordion();

To initialize a widget with options, use notation similar to the following:

$("#main-container").accordion({
    header : "#title-1"
    content : "#content-1",
    trigger : "#trigger-1,
    ajaxUrlElement: "a"
 });