jQuery: loading and executing code

jQuery's code can be loaded and executed either in the head or body elements. Putting your jQuery code in the head or body elements of a web page is not the same thing. Though many developers follow the second approach to improve the overall perceived performance of their pages, they're probably not completely aware of the existing differences between the two methods. Let's take a closer look at them.

When you put your jQuery code in the body section, together with the main reference to the jQuery library, using the ready() method is not required to load and execute your code:

<script type="text/javascript">
  $('#test').addClass('test');
</script>
</body>
</html>

or better, with a self-executing function:

<script type="text/javascript">
(function() {
   $('#test').addClass('test');
})();
</script>
</body>
</html>

This simply works, but if you try to do the same thing by putting your code in the head section, then you have to use the ready() method or it won't work:

<head>
<script type="text/javascript">
$(document).ready(function() {

  $('#test').addClass('test');


});
</script>
</head>

This happens because with the former method your jQuery code is parsed and executed together with all the markup structure of your document, whereas with the latter does not.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.