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()
.
Note
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
-
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:(Check out the documentation regarding scope in JavaScript for more details on this unique ID function name suffix.)<?php $uniqueSciptId = uniqid() ?> <script> function initMyComponent_<?= $uniqueSciptId ?>() { } </script>
-
Copy the contents of the original RequireJS module into the function.
-
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. -
Call the new function:
- If the code depends on customer section data, call the function as a
private-content-loaded
event subscriber. - 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 aDOMContentLoaded
event subscriber, to ensure thehyva
object is defined. If the template is rendered later in the page this is not necessary. - Otherwise, call the function inline.
- If the code depends on customer section data, call the function as a