Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  27] [ 1]  / answers: 1 / hits: 31627  / 7 Years ago, sat, march 11, 2017, 12:00:00

At my website, I am loading jQuery asynchronously.



In order to do that, I must run jQuery functions only after it is really loaded.



I've tried two pure JS ways:



<script src=js/jquery-2.2.2.min.js async></script>
<script>
window.addEventListener('load', function() {
//stuff
}, true);
</script>


And



window.onload = function() {
//stuff
}


But even so I still get Uncaught TypeError: $(...) is not a function at...



How do I fire jQuery functions after the lib is fully loaded?


More From » jquery

 Answers
9

You need to add the script only after jQuery library is loaded using script tag.





<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<script>
// your code should be here
alert(typeof jQuery)
</script>








The document ready handler is using to execute the code only after DOM elements are loaded.





<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<script>
console.log('Outside document ready handler ' + $('.test').length)

$(document).ready(function() {
console.log('Inside document ready handler ' + $('.test').length)
});
</script>
<div class=test></div>








UPDATE 1: You can use defer if script is in a file, refer following question: jquery loaded async and ready function not working






UPDATE 2: Or you can bind load event handler to the script tag using addEventListener method.





<script async id=script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<script type=text/javascript>
document.getElementById('script')
.addEventListener('load', function() {
alert(typeof jQuery)
});
</script>





FYI : I don't know why you are doing this, for optimizing the speed of content load it's always better to move the script tags at the end of body which helps to load content first.


[#58590] Thursday, March 9, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
earllutherf

Total Points: 412
Total Questions: 108
Total Answers: 102

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;