caliph caliph - 3 months ago 9
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='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?

Answer

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.

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

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>

Comments