Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Deferred loading of JQuery and '$ not defined'

I cannot wrap my head around this issue and the vast offer of information I found on the net:

On my project the JQuery is loaded with "defer". This I cannot change due to project standards.

<script defer src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js'></script>

Now I need to add some small functions to a page (currently inline):

With this setup the browser will try to execute the inline scrip before jQuery loads => "Uncaught ReferenceError: $ is not defined"

<body>
...
...
<script>
  $("#city").change(function() {...some stuff...};
  $("#doctor").change(function() {...some stuff...};
</script>
</body>

Whats the smart way to resolve this?

like image 804
caliph Avatar asked Aug 29 '16 12:08

caliph


People also ask

How do I fix resolve ReferenceError is not defined?

The most common reason behind the error "Uncaught ReferenceError: $ is not defined" is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you're executing the jQuery code only after jQuery library file has finished loading. Save this answer.

What is deferred () in jQuery?

Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.

Is not defined issue in jQuery?

You may experience the “jQuery is not defined error” when jQuery is included but not loaded. Make sure that it's loaded by finding the script source and pasting the URL in a new browser or tab. The snippet of text you should look for to find the URL to test.


2 Answers

Wrap it inside window.onload, so the script will only be executed when everything is fully loaded.

Try this example:

window.onload = function () {
    $("#city").click(function() {
        alert('city');
    });
    $("#doctor").click(function() {
        alert('doctor');
    });
}
<script defer src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js'></script>

<button id="city">City</button>
<button id="doctor">Doctor</button>

Explanation about window.onload from MDN:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links, and sub-frames have finished loading.

https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload


For more idiomatic (in jquery) way, use the code below. it's the same with window.onload.

$(document).ready(function() {
    // put code here
});

Another alternative, use $(function() { }).

$(function() {
    // put code here
})
like image 102
novalagung Avatar answered Oct 03 '22 21:10

novalagung


Pros: With this approach, you don't have to wait for the 'load' event to trigger.. this should execute as soon as jQuery has finished loading.

var initInterval = setInterval(function(){
        if(window.jQuery) {
            clearInterval(initInterval);
            init(); // where init is the entry point for your code execution
        }
    }, 20);


function init(){
  $('#example').text('Ahoy!');
}
<script defer src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js'></script>

<div id="example">Hi</div>
like image 37
Lucky Soni Avatar answered Oct 03 '22 20:10

Lucky Soni