Reputation: 1495
I am using this code at footer for Eliminate render-blocking resources
<script async or defer src="/jquery.js">
/* custom code */
<script>
$(document).ready(function(){
$('.menu-bar').click(function(){
$('.nav-bar').slideToggle();
});
$('.dropdown').click(function(){
$(this).toggleClass('inDrop');
$('.dropdown-menu').slideToggle('slow');
});
});
</script>
Now I am getting Uncaught ReferenceError: $ is not defined
error.
what is best way to use Asynchronous / Deferred JavaScript
Upvotes: 0
Views: 214
Reputation: 3440
Async is tough, because it'll execute the minute it finishes, so you can't tell the order in which scripts will finish being retrieved. It's also negligible compared to defer, which will wait until the HTML parses before it starts, and then it starts in order.
Here are two cases:
<HTML start>
<async js 1>
<async js 2 (dep on 1)>
<HTML parses>
<js 2 finishes and executes>
<js 1 finishes and executes>
<HTML finishes parsing>
Defer:
<HTML start>
<defer js 1>
<defer js 2 (dep on 1)>
<js 2 loads, and waits>
<js 1 loads, and waits>
<HTML finishes parsing>
<js 1 is fired>
<js 2 is fired>
You can keep your dependencies with defer
. I use defer 99.9% of the time, and only if the order of your scripts is not important.
If you need the inline js to wait until the dependencies are loaded, you would wait for the document ready state.
jQuery:
`$(document).ready(function() {
...code here...
};`
vanilla JS:
`document.addEventListener("DOMContentLoaded", function() {
...code here...
};`
Upvotes: 1