Skip to content

data-mage-init, x-magento-init and require()

Most JavaScript is inlined in Hyvä. This is in contrast to Luma, where scripts tend to be small external files.

Inlining scripts makes templates to self-contained UI components, that are easy to reuse, and also helps page speed.

If a large amount of JavaScript is needed, it of course can be moved to an external file.

That said, in most cases external JavaScript is inlined in Hyvä. This will mostly mean removing x-magento-init and/or data-mage-init declarations. The same applies to inline calls to require() .


More on the decision why Hyvä mainly uses inline JavaScript rather than external files can be found in the FAQ.

Process for inlining external scripts

  1. In the .phtml template, declare a new function. If there is any chance the template will be rendered multiple times on the page, it can make sense to qualify the function name with a unique ID:

    <?php $uniqueSciptId = uniqid() ?>
     function initMyComponent_<?= $uniqueSciptId ?>()
    (Check out the documentation regarding scope in JavaScript for more details on this unique ID function name suffix.)

  2. Copy the contents of the original RequireJS module into the function.

  3. Replace any dependencies. Most of the time they can simply be removed (e.g. jQuery or $.mage.cookie), but sometimes it might require inlining another external JavaScript module.

  4. Call the new function:

    1. If the code depends on customer section data, call the function as a private-content-loaded event subscriber.
    2. If the code is rendered in the page header and depends on a function from the global window.hyva object (e.g. hyva.getCookie), then it should be called as a DOMContentLoaded event subscriber, to ensure the hyva object is defined. If the template is rendered later in the page this is not necessary.
    3. Otherwise, call the function inline.