2

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?

  • use this in Head tag <script src="jquery.js" /> <script src="js/myfile.js"/> – Sourav Apr 5 '18 at 3:25
  • jquery is allready loaded but after my.js, why sould i load it twice? – krybbio Apr 5 '18 at 3:37
  • I have added custom js in Custom theme that loading last of all js. but how you are adding js files? – Sourav Apr 5 '18 at 4:25
  • @krybbio Please, accept the Answer which really helps you. So, it helps other to find the best answer. – Emipro Technologies Pvt. Ltd. Apr 5 '18 at 13:52
  • @EmiproTechnologiesPvt.Ltd. for my need all of them are equals and usefull but my solution in EDIT 2 is different and for me is the best way. Should I post it as the accepted answer? – krybbio Apr 5 '18 at 14:27
1

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

  • Probably this is the best way. In my case i used "js/homepage": {} instead "Vendor_Module/js/homepage": {} as my js whas in theme. – krybbio Apr 8 '18 at 14:19
  • Yes, that's completely your choice. You can use any path. :) – Dinesh Yadav Apr 9 '18 at 4:15
2

You can add your js file by adding it to the cms_index_index.xml in the head tag

Go to this path

app/design/frontend/yourspacename/yourtheme/Magento_Cms/layout/cms_index_index.xml

then add it like this

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
         <head><script src="js/myfile.js"/></head>
    </body>
</page>

you can use this also

require(['jquery', 'jquery/ui'], function($){ 
  'use strict';
  $(document).ready(function(){
    alert('hello');
     //your js code here  });

 });

Need to make entry in requirejs-config.js

var config = {
    map: {
        '*': {
            myfile: 'Custom_Module/js/myfile'
        }
    }
};
  • ReferenceError: jQuery is not defined – krybbio Apr 5 '18 at 2:52
  • Use $ sign instead Jquery. – Sourav Apr 5 '18 at 2:54
  • function($){ .. You using $ sign so use $. – Sourav Apr 5 '18 at 2:55
2

You are doing this in wrong way. Magento uses requirejs to load the js dependencies asychronously. This means, js dependencies are loaded only when it really requires. Jquery is also treated as a requirejs module.

So if you want to load your script directly, then instead of defining it in a separate js file, you need to include your code in a phtml file. This is because a separate js file is needed only when you need to create requirejs module.

So here the first step is, add a phtml file in your cms page layout. This is how you should do it:

File: app/code/Namespace/Module/view/frontend/layout/cms_index_index.xml

<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="page.wrapper">
            <block template="Namespace_Module::script.phtml" class="Magento\Framework\View\Element\Template" name="my.script" />
        </referenceContainer>
    </body>
</page>

Here you included the script.phtml file inside the home page layout. Now it is the time to define this phtml file

File: app/code/Namespace/Module/view/frontend/templates/script.phtml

<script type="text/javascript">
    require(["jquery"], function($){
       //my code
    });
</script>

So what is the real difference here? Your script is now loaded in the body and hence requirejs and jquery is available to your script. This way your script will be executed without any problem.

PS: Here I assume, you have a working module with name Namespace_Module. You can also add your layout file via theme too. There are many ways to accomplish the desired scenario.

2

Please follow below steps you will get solution.

Step-1: Need to create requirejs-config.js in your module.

Now in this file add below code:

 var config = {
     map: {
        '*': {
             myjs: 'Magento_Theme/js/my'
        }
    } };

Here you can use any module instead of 'Magento_Theme'

Step: 2 Create/add js file in Magento_Theme/web/js/my.js

In your js file add js code inside define function:

 define(['jquery'], function($) {
        'use strict'; 
    //your custom js code; 
 });

Step:3 Run below commands.

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy

Step:4: Add/call your file in your home page content.

 require(["jquery",'myjs'], function($){
   //your code
});

Hope it will useful to you.

  • You did extra steps that are not required. Step-1: Need to create requirejs-config.js in your module. For this need to create new extra module. he need just extra js file to homepage. – Sourav Apr 6 '18 at 2:57
  • @Sourav We have added just because of in future it'll help someone else also. – Emipro Technologies Pvt. Ltd. Apr 6 '18 at 7:14
1

Go to this path

app/design/frontend/yourspacename/yourtheme/Magento_Cms/layout/cms_index_index.xml

<head>

 <script src="js/jquery.min.js"/>

 <script src="js/owl.carousel.min.js"/>

 </head>

Go to this path app/design/frontend/yourspacename/yourtheme/web/js. Create custom.js in js folder.

require(['jquery', 'jquery/ui'], function($){ 
  'use strict';
  $(document).ready(function(){
    alert('hello');
     //your js code here  });

 });

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

enter image description here

0

Thanks all you guys.

The easiest way to add javascipt in home page for me was

<script src="{{view url="js/my.js"}}"></script>

in the end of cms content.

requirejs-config.js not needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.