0

I have read a number of ways to add JS files to a Magento 2 project, but I haven't seen anywhere where the benefits / best use-cases for each are explained.

The use-cases that are most relevant to my projects are:

  • Adding a JS library (eg. Owl Carousel)
  • '' my own JS file with some basic click events and references to the above library.

And the init methods available (to my knowledge) are:

  • Adding a file through requirejs-config.js and referencing it in a template file where needed.
  • '' in an xml file within tags.
  • '' via the Magento x-init method.

I assume that each method has a best use case due to the fact that there seem to be a few options.

Could anyone give a brief explanation or a link where the benefits/ use-cases are broken down?

1 Answer 1

5

I would prefer to use RequireJs in your use case. Magento 2 has better-perceived better-perceived page loading time through the RequireJS because it allows JavaScript to load in the background (asynchronous or “lazy” JS loading).

As per my views, Magento provides a standard mechanism to discourage directly embedding javascript into a page. So they have introduced text/x-magento-init script tag with an * attribute, it will

  • Initialize the specified RequireJS module (Magento_Ui/js/core/app)
  • Call the function returned by that module, passing in the data object

Magento itself often uses the x-magento-init method to invoke a RequireJS module as a program. However, the real power of x-magento-init is the ability to create a Magento JavaScript Component.

For "in an XML file within tags", you can use this method to simplify your development. As a side note, if you can avoid putting the js in the head then this will case render blocking until the js has been fully downloaded.

You can read more about JS components in Alan Storm's blog. Good read though.

https://alanstorm.com/magento_2_javascript_init_scripts/

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.