Magento 2 – Fix ReferenceError: jQuery is Not Defined

jquerymagento2

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.

Best Answer

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');

    });

});