0

How to get JS file in the blocks,

How to declare like:

<script type="text/javascript"> 
    src="{{skin url=''}}js/my_custom.js">
</script>

My JS path:

app/design/frontend/Codazon/fastest/grocery_gourmet/web/js/my_custom.js

OR Recommended way to declare JS.

3
  • Do you want to add js on page? Aug 30, 2020 at 7:05
  • Yes, In block I just created slider , I want add js for this slider.
    – zus
    Aug 30, 2020 at 7:17
  • I just pasted my JS to app/design/frontend/Codazon/fastest/grocery_gourmet/web/js/my_custom.js How to get JS path in block.
    – zus
    Aug 30, 2020 at 7:23

1 Answer 1

0

In Magento 2, you need to add and declare your js file via RequireJS

So:

app/design/frontend/Codazon/fastest/requirejs-config.js

var config = {
    map: {
        '*': {
            myscript: 'js/my_custom'
        }
    }
};

app/design/frontend/Codazon/fastest/web/js/my_custom.js

define(['jquery'], function($){
   "use strict";
       return function myscript()
       {
           alert("Yes, it woooorks!");
       }
});

app/design/frontend/Codazon/fastest/Magento_Theme/templates/{yourfile}.phtml

    <script>
        require(['jquery', 'myscript'], function($, myscript) {
            myscript();
        });
    </script>

PS you also need to:

  • clean the cache => php bin/magento c:c

  • clean var/view_preprocessed content => rm -rf var/view_preprocessed/*

  • clean pub/static content => rm -rf pub/static/*

  • deploy the static content = php bin/magento setup:static-content:deploy -f

Good luck!

6
  • and how to set js path inside the block.
    – zus
    Aug 30, 2020 at 13:19
  • In Magento 1 inside the block declared like this => <script type="text/javascript" src="{{skin url=''}}js/my_custom.js"></script>
    – zus
    Aug 30, 2020 at 13:20
  • Which block ? can you share the path of that block ?
    – PЯINCƎ
    Aug 30, 2020 at 13:22
  • Block => snipboard.io/7ZY2wm.jpg and i want add js path => snipboard.io/HsEUVY.jpg
    – zus
    Aug 30, 2020 at 13:29
  • Ah, you mean a CMS Block, I have never used this way to put the js file directly in the cms block to avoid the terrible errors of requirejs, I advise you rather to follow my solution then to call the phtml rather than the jssomething like : {{block class="Magento\Framework\View\Element\Template" name="customblock1" template="yourfile.phtml"}}you need probably to change the block class
    – PЯINCƎ
    Aug 30, 2020 at 13:41

Your Answer

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

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