'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?
Solution 1:[1]
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
})
Solution 2:[2]
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>
Solution 3:[3]
This way you can add multiple functions to window.load
:
window.addEventListener("load",function(event) {
$("#city").click(function() {
alert('city');
});
},false);
window.addEventListener("load",function(){
$("#doctor").click(function() {
alert('doctor');
});
},false);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | datasn.io |