5

My steps:

1) Load my file slider.js to: app/design/frontend/Vendorname/default/web/js.

2) Create requirejs-config.js to: app/design/frontend/Vendorname/default

var config = {
        paths: {
            slider:        "js/slider"
        },
        shim: {
            slider: {
                deps: ["jquery"]
            }
        }
    }; 

3) rm -R pub/static/*

4) bin/magento setup:static-content:deploy

When I open site, slider.js is not loaded. I need to call him, that he began to load? I read a lot of Magento 2: Javascript Init Scripts, Use custom JavaScript.

Realy need help.

2 Answers 2

9

The Way you are including custom js in requirejs-config-js is correct , but you must need to load this js in your template(.phtml) file.

Add below code in your .phtml template file :

<script type="text/javascript">

    require(['jquery', 'slider'],function($){
        (function() {
             //code goes here
        })(jQuery);
    });
</script>     
2
  • If I write this in site-admin-panel/home-page/content. Will it work?
    – Sylon
    Dec 26, 2016 at 4:52
  • Yes it will work . You can call your slider block in homepage as well Dec 26, 2016 at 4:58
3

Magento 2 uses RequireJs to load the js. So, our custom script will not load until we call it via RequireJS. For example, in your phtml, we can call

        <script>
            require([
                "jquery",
                "slider"
            ], function($, slider){

               ......

            });
        </script>
2
  • If I write this in site-admin-panel/home-page/content. Will it work?
    – Sylon
    Dec 26, 2016 at 4:56
  • Yes, may will work. Dec 26, 2016 at 4:57

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.