I\'ve seen in several plugin instructions , paste the javascript/jQuery source just before the end of body tag. I made search why they are saying like that, didn\'t make m
If javascript code does not reference the DOM or any objects in the DOM, then it can be put anywhere in your page.
If you put it AFTER the HTML in the body tag right before the </body>
tag, then the page will be parsed and displayed before your scripts load which will get your page displayed faster. So, the recommendation you've seen is to maximize the initial display performance of your pages.
If javascript DOES reference the DOM or any objects in the DOM, then it must either have special code to wait for the DOM to be loaded before executing using something like $(document).ready(fn)
in jQuery or the code must physically be loaded after the DOM so that it won't execute until the DOM is loaded.
And, of course, code must be loaded after any code that it's initial execution immediately depends upon. So, a jQuery plugin would need to be loaded after the jQuery library itself.
Here's a general set of guidelines:
<head>
section only if that code needs to execute or be used before the document loads. As an example, if you had code that was examining the URL and cookie and deciding whether to do a client-side redirect, you want that code to execute immediately so you might put that code in the <head>
section so it can execute before the DOM loads or displays. As another example, if you have some inline javascript that needs certain functions to be available during the page load (e.g. some inline javascript that does document.write()
and calls some utility functions), then put those utility functions in the <head>
section so they are available as the page loads.</body>
tag to optimize page display time and position the code where the DOM is ready for manipulation when the code runs.