How to insert some JavaScript to a *.phtml template in the proper way (x-magento-init)

phtml
x-magento-init
javascript
(Dmitry Fedyuk) #1

Of course you can insert some JavaScript into a *.phtml template by using plain <script type="text/javascript"> tag but sometimes it does not work as expected because of a wrong initialization order.
I had such problem with SimpleMDE JavaScript Markdown Editor.
Magento 2 contains a lot of complex JavaScript code and it is much safier to insert your JavaScript code in the proper and officially recommened way by using x-magento-init syntax.

An example:

<script type="text/x-magento-init">
	{"*": {"Dfe_Markdown/main": {}}}
</script>

Dfe_Markdown/main refer to the JavaScript file in Dfe/Markdown/view/<area>/web/main.js folder.
An example of such file:

require([
	'jquery', 'SimpleMDE', 'HighlightJs'
], function($, SimpleMDE, HighlightJs) {$(function() {
	// Your custom code here...
});});
0 Likes

How to load a JavaScript on demand using RequireJS
domReady!: a useful RequireJS plugin to ensure the DOM is loaded before your Magento 2 JavaScript execution
How to pass parameters from *.phtml to a JavaScript component using x-magento-init
How to add JavaScript / CSS / Less with a custom module
How to load JavaScript or stylesheet conditionally depends on backend config settings?
How to pass parameters from *.phtml to a JavaScript component using x-magento-init
(Dmitry Fedyuk) #2

See also:

0 Likes