0

We currently have a large phtml file that is essentially a plain JavaScript file, eg.,

<?php
  // some conditional check. about 10 lines of code
>

<script>
// here is 1000 lines of JavaScript
</script>

We want so split JavaScript into separate file so editor can have syntax highlight and we can run linters on JS file. What is the best way to split JS file into separate file but at run time still inline JavaScript code (so client doesn't have to fetch separate JS file)?

  • Write all script codes in new js file. And call that js file from layout XML. – Dhaduk Mitesh Nov 6 '19 at 6:39
  • I'm noob to magento. how can I call js? Do I just echo? – Kazuki Nov 6 '19 at 6:41
  • Have you created any file in view/frontend/layout/? – Dhaduk Mitesh Nov 6 '19 at 6:45
  • yes currently I'm loading phtml from layout XML. I now understand you're suggesting I can directly load js file - that makes more sense. Is there a way for me to still control whether I inject js or not based on some php? – Kazuki Nov 6 '19 at 6:47
  • Please add this in XML: <head> <script src="Vendor_Module::js/newfile.js"/> </head> and move all script code to this js file. – Dhaduk Mitesh Nov 6 '19 at 6:49
1

Please add this code in layout XML view/frontend/layout/

<head>
    <script src="Vendor_Module::js/newfile.js"/>
</head>

Or else add below script in php,

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $repo = $objectManager->get('\Magento\Framework\View\Asset\Repository');
?>
<script type="text/javascript" src="<?php echo $repo->getUrl("MyModule::js/my.js") ?>"></script>

And move all script code to this js file. And then check it.

0

In my case I wanted to place script at before.body.end and I had some php logic so I wanted to keep phtml. I end up having phtml like

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$repo = $objectManager->get('\Magento\Framework\View\Asset\Repository');

?>

<script type="text/javascript" src="<?php echo $repo->getUrl("MyModule::js/my.js") ?>"></script>

and I put my.js file in view/frontend/web/js

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.