caliph caliph - 1 year ago 68
jQuery Question

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=''></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"

$("#city").change(function() {...some stuff...};
$("#doctor").change(function() {...some stuff...};

Whats the smart way to resolve this?

Answer Source

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

window.onload = function () {
    $("#city").change(function() { /* ...some stuff... */ });
    $("#doctor").change(function() { /* ...some stuff... */ });

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.

Try this example:

window.onload = function () {
	$("#city").click(function() {
	$("#doctor").click(function() {
<script defer src=''></script>

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download