How to Add Custom JS to Magento 2 Theme

javascriptmagento2

Im following the answer provide by Andrea on How To add JS file in frontend for all pages

However I am recieving the follow error and unsure how to resolve?

require.js:1895 GET http://domain.dev/products/pub/static/version1497347169/frontend/aa/aa-theme/en_US/js/main.js

require.js:166 Uncaught Error: Script error for: js/main
http://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:166)
at HTMLScriptElement.onScriptError (require.js:1681)

Could anyone please help with getting a custom script added?

Update:

I've tried to include libraries into my require_config.js like:

var config = {
paths: {  
        'accessible-menu': "Magento_Theme/js/accessible-menu/accessible-menu",
        'slick': "Magento_Theme/js/slick/slick.min"
    },   
shim: {
    'slick': {
        deps: ['jquery']
    },
    'accessible-menu': {
        deps: ['jquery']
    }
}
};

And have added my main scripts file into my default.xml like:

<referenceContainer name="before.body.end">
        <block class="Magento\Framework\View\Element\Text" name="scripts.min.js">
            <arguments>
                <argument name="text" xsi:type="string"><![CDATA[<script type="text/javascript" src="http://domain.dev/app/design/frontend/aa/aa-theme/Magento_Theme/web/js/scripts.min.js"></script>]]></argument>
            </arguments>
        </block>
    </referenceContainer>

Just doesn't seem to be loading the libraries but my scripts.min.js is included?

Best Answer

Have you done the following?

  • Clear Magento cache
  • Clear browser cache
  • Delete the following directory
    • var/pre_processed
    • pub/static/frontend
    • pub/static/_requirejs
  • Reload the page

The majority of the time I see errors like this it's because of caching and/or symlinks.

 Update

Thanks for including your code, I think this is happening because you are adding JS via XML. This is no longer the best way to add JS in Magento, you should take a look at Require JS.

The require_config.js does not load JS file, all you've done there is add aliases and dependencies for your scripts.

To load an actual script you need to use either x-magento-init or data-mage-init. Read here for the full info.

I think you need to do something along these lines:

In your PHTML template:

Replace * with your element ID/Class.

<script type="text/x-magento-init">
{
    "*": {
            "slick": {}
    }
}
</script>

Initialise Slick Initialise Slick in here.

define(['jquery', 'slick', 'domReady!'], function($, slick) {
    'use strict';

    $('.your-element').slick();
});
Related Topic