AnswerBun.com

Magento 2 - How to add custom JS file path into CMS Block

Magento Asked on December 8, 2020

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.

One Answer

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!

Answered by PЯINCƏ on December 8, 2020

Add your own answers!

Related Questions

Magento 2 cache_invalidate loop

2  Asked on January 29, 2021 by tjitse

     

Magento 2.2 ssh commands not executed

1  Asked on January 29, 2021 by jilco-tigchelaar

   

How to add new or customize existing top header links in Magento?

4  Asked on January 26, 2021 by tallal-hassan

     

Upload SVG files as product image

0  Asked on January 26, 2021 by francesco-terreni

         

Add custom parameter in order’s item in rest api magento 2

0  Asked on January 25, 2021 by vijay-gupta

 

Special Price suddenly not showing

1  Asked on January 23, 2021 by dickson

 

How to activate product navigation in Magento 2?

2  Asked on January 22, 2021 by morison

     

Quote with no items – add to cart error

1  Asked on January 22, 2021 by fra

     

Magento 2 get cart items in block class

1  Asked on January 20, 2021 by khooshbu-patel

   

Magento custom option text field max length

1  Asked on January 19, 2021 by k-i

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir