Can JavaScript be cached if it is in the body tag

2019-09-04 07:57发布

问题:

I am reading this How to make HTML rendering fast it says that scripts in the HEAD tag can be cached.

Can JavaScript in the BODY tag be cached? If not, why does YUI recommend putting scripts in the body tag?

回答1:

The code will be cached if you cache the entire HTML page, not otherwise. HTML pages are usually dynamic these days (generated by scripts and CGIs) and therefore not possible to cache without sacrificing functionality. Therefore you usually want to place JS code in external files which then can be cached by setting HTTP cache headers for the JS file.

The answer, for the most part, is that you cannot cache JavaScript which is inlined into the HTML code (in the HEAD section or otherwise). To make it cacheable you need to put it in an external file, but then the browser will need to do an extra HTTP request to get the JavaScript the first time.



回答2:

JavaScript will be cached (and reused between pages) if it is in an external file and the cache control headers say it should be cached.

It may be cached if it is embedded in the page itself (i.e. between <script> and </script> instead of at the end of src="..."), but only if the entire page is cached and it will not be reusable between pages.

It makes no difference, to caching, if the <script src="..."></script> is in the head or body.



回答3:

Mate, I think you might have misunderstood what Rich said. He said put the JavaScript into an external file and link it from the head.

This is in contrast to placing the JavaScript into a script tag in the body of the page.

It would be reasonable to put JavaScript into a script tag in the page body if it is used only on that page. In fact, if its used only one that page, it would not be an optimisation to place it into an external file. The additional GET request for the JS file will be almost simultaneous on Firefox, Opera, Safari but not on IE6. The reason is that IE6 has only a few (2) threads to use for fetching files, whereas Firefox has up to 16. That is why having a separate file for page-specific code would be a step backwards because it might actually slow down the page load.

If however, you have a common JavaScript file that you want to use on many pages then you should definitely place it in an external file and link it from the head, because it will be cached the first time any of those pages are loaded, and it will not need to be fetched again when any of the other pages use it. The bigger the file, the bigger the advantage to caching it.

I think that was the point he was making. Does that help?