[Solved] why my jquery not work without $(function() { in head?


To answer the question: “why my jquery not work without $(function() { in head?”

It won’t work because $(function(){ is a shortcut for $(document).ready(){ which basically says “once all of my HTML is fully loaded, then run this script”. without the $(function(){, your script tries to run as soon as it’s loaded. Since it’s in the head of the document, it tries to run before your element with class=”nc” exists. It cannot attach an event handler to an element that doesn’t yet exist. So wrapping it in $(function(){ allows it to work even if it’s in the head of the document as long as your script appears after the script tag that loads jquery.

That being said it’s considered best practice to move as much javascript loading to the bottom of your page to improve loading times, especially scripts that you don’t intend to run until the DOM is loaded anyway.

0

solved why my jquery not work without $(function() { in head?