JavaScript – How to Add JS to Home Page in Magento 2.2

javascriptjquerymagento2.2requirejs

I need to add some jQuery script to home page.

Following docs:
http://devdocs.magento.com/guides/v2.2/javascript-dev-guide/javascript/js-resources.html

I have my.js file with inside:

require(["jquery"], function($){
   //my code
});

but in the console i've got thi error:

TypeError: require is not a function

Which is the correct way to add e js file in the homepage only?

EDIT:

the problem seems to be that the js is loaded before all the others, including jquery, when it is inserted in the <head> tag

How to make it to be load at the end of the que?

Best Answer

We should use the javascript init method for adding the javascript to our page.

Javascript init method helps you to solve few problems.

  • They provide a standard mechanism to discourage directly embedding javascript into a page.

  • They provide a way to invoke a standalone RequireJS module (defined with define) as a program.

  • They provide a way to pass that program a server-side generated JSON object.

  • They provide a way to tell that program which (if any) DOM nodes it should operate on.

You can get more info here https://alanstorm.com/magento_2_javascript_init_scripts/

Now let's use this in your case.

Navigate to

Magento Admin > Content > CMS Pages > Homepage

Add following code in the content of homepage.

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

Now create a homepage.js file

app/code/Vendor/Module/view/frontend/web/js/homepage.js

Add following code in the file

define([
    'jquery'
], function (jQuery) {
    'use strict';

    return function (config) {
        alert(jQuery('body').attr('class'));
        // add your jQuery script here
    }
});

Run command php bin/magento setup:static-content:deploy

Related Topic