5

I am trying to add custom jquery code into my module but it is not working.

app/code/Custom/Module/view/frontend/web/js/my.js

jQuery.noConflict();
jQuery(document).ready(function(){
    alert('ok');
});

app/code/Custom/Module/view/frontend/layout/default.xml

<?xml version="1.0" encoding="UTF-8"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="Custom_Module::js/my.js"/>
    </head> 
</page>

In console, I am getting the error message

ReferenceError: jQuery is not defined

How to fix this issue.

  • 2
    if using Requirejs, shouldn't use jQuery document ready: stackoverflow.com/questions/15332628/… – Khoa TruongDinh Jan 13 '17 at 13:05
  • You should avoid adding JS this way, you should use Require JS within M2. – Ben Crook Jan 13 '17 at 16:45
  • @KhoaTruongDinh great info – Bilal Usean Jan 27 '17 at 8:00
  • @Anshu Mishra did you manage to solve this? – vbak May 16 '17 at 18:32
  • @vbak I have already posted my answer. – Anshu Mishra May 17 '17 at 4:53
10

Magento2 use requirejs concept (lazy load) so load jquery first then write your jquery code.

e.g)

require(['jquery'],function($){

    $(document).ready(function(){

       alert('ok');

    });

});
  • Using above code, I am getting TypeError: require is not a function – Anshu Mishra Jan 16 '17 at 4:32
4

We need to use Requirejs to load the jQuery dependency. Your js should be:

app/code/Custom/Module/view/frontend/web/js/my.js

require([
    "jquery"
], function ($) {

   // your code here

});
  • Using above code, I am getting TypeError: require is not a function – Anshu Mishra Jan 16 '17 at 4:32
  • Try to add the js in default_head_blocks.xml – Khoa TruongDinh Jan 16 '17 at 4:36
  • Still getting the same error message, TypeError: require is not a function – Anshu Mishra Jan 16 '17 at 4:54
4

The issue was that there is no sequence tag defined in the module.xml.
I have added Magento_Theme module in the sequence tag in my module.xml as follows

<sequence>
    <module name="Magento_Theme"/>
</sequence>

Secondly, I have added requirejs-config.js in my module's web directory.

var config = {
    map: {
        '*': {
            my: 'Custom_Module/js/my',
        }
    }
};

Third, I have modified the content of my js file as follows :

define('js/theme',['jquery', 'domReady!'], function(jQuery){
    alert('ok');
});

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.