1

I try to add a custom js to magento 2 head, but after the jquery.js. Or is there a way to add the custom js file to the footer?

I have tried in the default.xml but it's over the jquery.js

This is my code in default.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <body>
    <script src="js/myjsfile.js"/>
  </body></page>
4
  • please show your actual code, which you have tried. Commented Mar 14, 2017 at 10:17
  • I have added the code to my question. Commented Mar 14, 2017 at 10:22
  • you can do it using requirejs-config.js file to call after jquery. Commented Mar 14, 2017 at 10:23
  • ok, and without requirejs-config.js? Is there a way? Commented Mar 14, 2017 at 12:37

3 Answers 3

2

You should use Require JS to add the JS, loading it via the XML is not best practice. This is because Require JS can track dependencies and only load scripts when required, instead of unnecessarily loading scripts and creating a maze of confusing dependencies.

To load JS via Require JS follow these steps:

Template:

In your template add:

<script type="text/x-magento-init">
{
    // components initialized on the element defined by selector
    "<element_selector>": {
        "<js_component1>": ...,
        "<js_component2>": ...
    },
    // components initialized without binding to an element
    "*": {
        "<js_component3>": ...
    }
}
</script>

Where <js_component#>is the path to your JS, or alternatively the name of the module if you've mapped it with Require JS.

Script

Then write your JS inside Require like so:

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

See http://devdocs.magento.com/guides/v2.1/javascript-dev-guide/javascript/js_init.html for more info.

0

1.Map In requirejs-config.js of your module:

var config = {
    map: {
        '*': {
            'module-name': 'path/to/script'
        }
    }
};

Don't use .js at the end of the script

2.Html.

<div data-mage-init='{"module-name":{}}'>
   <!-- Stuff -->
</div>

3.Your Script

//path/to/script.js

define(["jquery"], function($){
    //Your stuffs
});

If you put "jquery" as a dependency in your definition function your script will be loaded before jquery

-2

I found a way to add the custom js file to the footer.

By adding the js file into the requirejs-config.js and also in the default.xml.

1
  • 1
    You have no need to include your script in layout file if you use require. Commented Mar 15, 2017 at 10:42

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.