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?

  • 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 Nov 26 '19 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 Nov 26 '19 at 5:06
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
    }
});
  • This is basically my current setup - i'd like to inline JavaScript to avoid asynchronous loading of JS file. – Kazuki Nov 26 '19 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>
  • 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 Nov 26 '19 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 Nov 27 '19 at 7:35
  • I believe it would still cause additional HTTP request to get server. – Kazuki Nov 27 '19 at 22:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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