Magento 2 Inline Javascript – Best Practices and Implementation

javascriptmagento-2.1magento2

Hoping someone's come across this before. I'm trying to get some javascript added to a phtml file in Magento 2, but instead of interpreting it as javascript it seems to be outputting it as plain text.

Initially I tried to get it working by using the usual javascript tags in the template file

<script type="text/javascript">
        $("#countdown-before")
            .countdown("<?php echo $this->start;?>", function(event){
                $(this).text("<?php echo $this->beforeMessage;?>" + event.strftime('%H:%M:%S'));
            })
</script>

When this output straight to the page I did some research and tried formatting it using reactjs, but had the same problem (not parsing the script tag and instead outputting as text)

<script>// <![CDATA[
        require([
            'jquery'
        ], function ($) {
            console.log('hello world');
        });
    // ]]>
</script>

Is there something I'm missing which is needed with Magento 2 in order to include javascript directly in the template page?

Thanks in advance

edit: Couple of extra details I realised might affect this. The issue is happening on an Enterprise Edition installation and the template file this is stored in is loaded via a widget. Don't know if maybe there's some sanitisation being applied because it's a widget and that's maybe what's breaking it

Best Answer

I suggest adding javascript through x-magento-init like below. It ensures that your javascript isn't render blocking. x-magento-init is the Magento 2 standard. Do something like

  <script type="text/x-magento-init">
        {
            "*": {
                "<Vendor_Module>/js/hello.js": {}
            }
        }
</script>

now in hello.js you can write whatever you want to. Again this make sure your javascript isn't negatively affecting page speed.

Your javascript then will look something like

define(['jquery'],function($){
    return function(){
        //do something
    }
});

It might look like too much for simple things but it pays to do it this way

Related Topic