0

Is it possible to inline JavaScript file into phtml file? we have phtml file in view/frontend/template/js and js file in view/frontend/web/js

<!-- current setup -->
<script type="text/x-magento-init">
  { "*" : {
    "MyModule/js/my_js" : {} }
  }}
</script>

Currently we use x-magento-init but we want to make script inline like below:

<!-- what we want -->
<script type="application/javascript">
  // my code from JS file is inlined here
</script>

We realize this is render-blocking but we'd rather want to do this because we need this script for determine what to render. Is there any standard way to achieve this?

2
  • It's possible to use inline JS but it's considered bad practice. What is the problem with using x-magento-init ? devdocs.magento.com/guides/v2.3/javascript-dev-guide/javascript/…
    – Holly
    Commented Nov 26, 2019 at 2:38
  • @Holly This particular script determines what is rendered on page so we want to load it as part of html to reduce latency - I know asynchronously loading JavaScript is best practice but in this particular case we'd like to load little script as inline. If you would load script inline from another .js file, how would you do it? Simply open file and echo?
    – Kazuki
    Commented Nov 26, 2019 at 5:06

2 Answers 2

1

Do something like :-

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

Your hello.js javascript then will look something like

define(['jquery'],function($){
    return function(){
        //do something
    }
});
1
  • This is basically my current setup - i'd like to inline JavaScript to avoid asynchronous loading of JS file.
    – Kazuki
    Commented Nov 26, 2019 at 17:04
0

Try below code on .phtml file.

<script type="text/javascript">
require(['jquery'], function(jquery) {
    jquery(document).ready(function(){
         /** Do Something **/
    });
});
</script>
3
  • I want to have separate phtml and js file so my editor can properly highlight js syntax. is there a way for printing-ing js file in phtml at rendering time?
    – Kazuki
    Commented Nov 26, 2019 at 17:05
  • There have different ways to call an js file in .phtml file. You can create a js file inside custom theme web folder. Add above code inside js file then call it at default_head_blocks.xml file with below code - <script src="Magento_Theme::js/sample.js"/>
    – Mousam Roy
    Commented Nov 27, 2019 at 7:35
  • I believe it would still cause additional HTTP request to get server.
    – Kazuki
    Commented Nov 27, 2019 at 22:46

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.