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




<?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">
        <script src="Custom_Module::js/my.js"/>

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

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






| improve this answer | |
  • 1
    Using above code, I am getting TypeError: require is not a function – Anshu Mishra Jan 16 '17 at 4:32

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

    <module name="Magento_Theme"/>

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){
| improve this answer | |

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


], function ($) {

   // your code here

| improve this answer | |
  • 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

I had the same problem. Yesterday everything worked just fine but the next day I suddenly get "ReferenceError: jQuery is not defined"

I did no changes, I even checked out an older commit where everything worked fine. It was because of a script which was not wrapped in require(['jquery', 'domReady!'], function($){ ... even though the same script worked yesterday without it. Very strange.

| improve this answer | |

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.