简体   繁体   中英

Putting jQuery/javascript source pages before end of body tag

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 me any sense.

If I put the src file where ever in the script, I never faced a problem at all. Could anyone give me a good answer about this?

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:

  1. Put code as late as possible in the page to maximize the display performance of your page.
  2. Put code after any other libraries that its initial execution depends on.
  3. Put code in the <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 (eg 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.
  4. If there is no reason to execute the code before the page loads or if the code needs to access the DOM itself, then put the code right before the </body> tag to optimize page display time and position the code where the DOM is ready for manipulation when the code runs.
  5. Put code in external JS files whenever possible to take maximum advantage of browsing caching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM