Why put JavaScript in the footer of a page?

2019-04-10 20:10发布

问题:

So I recently bought and downloaded a template from ThemeForest. I set up the template on my local server. I generated the navigation, which has dropdown menus, with codeigniter. I had everything in the menu coded correctly. I only had the header generated and went to test it out and realized the dropdown menus were not working. I spent about two hours trying to figure out what was wrong with my code. Then I finally realized that the JavaScript files were included in the footer of the template... which I had not yet generated.

So my question is... why would someone put JavaScript files in the footer of an HTML page? I thought that JS was only supposed to be located in the header of the file. Right?

回答1:

There are different ways you could load a script file to a web page.

But loading scripts at bottom of you page have the following advantages.

  1. Will not block any DOM content to be loaded.
  2. All the DOM elements will be available for the scripts that are being loaded.
  3. If you are using third-party libraries such as jQuery, you can skip the $(document).ready(function () {...}); as the DOM is already loaded.

Hope this helps.



回答2:

Javascript can run every where in your page. not only in header!

But, best for your page speed is put script at bottom (before body closing tag).

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

Readmore: http://developer.yahoo.com/performance/rules.html#js_bottom



回答3:

The big problem with scripts at the bottom is that you cannot have any scripts in the middle of the page (which is a problem with dynamically generated pages) and any page-specific script you want to apply to elements on the page you need to put after loading in your libraries. If, for example you need to load in some ajax content you can only do that after the bottom JS has been loaded. So for many reasons people prefer to have the libraries at least loaded at the top (head) then only put manipulating JS at the foot