0

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

4
  • You can't have code inside a script with src. They need to be separate <script> tags. Commented May 16, 2020 at 6:25
  • And you can't use async if you need to use the library in another script tag. Commented May 16, 2020 at 6:26
  • @Barmar , Yes i was forgot to add here. i updated code now. Commented May 16, 2020 at 6:30
  • You need to break your script tag on top as well. Commented May 16, 2020 at 6:46

1 Answer 1

1

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...
};`
Sign up to request clarification or add additional context in comments.

5 Comments

<script defer src="/jquery.js"> /* custom code */ <script defer > $(document).ready(function(){ }); </script> is this code correct ?
Edit I misread. Yes. Calling jQuery first and both deferred will make it stay dependent.
its working if i use JS file for custom code. but not working for inline js code
Well yes. Because inline js is in the HTML that's being parsed. You can't defer a library the inline HTML depends on because it would defer behind the inline code.
What you would do is wrap your code in a loaded/ready state. Like this: $(document).ready(function() { ...code here...} without jQuery: document.addEventListener("DOMContentLoaded", function() { ...code here... };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.