1.在以往的做法中,像<script src=”js文件位置”></script>这样的JS文件外链声明通常会放在head标签里面。这样做是为了把像CSSJS这种外链文件声明放在统一的位置以达到文件的规范性。然而,浏览器在解释HTML文件时是一行接着一行进行解析的。假如一个页面包含了多个JS文件,JS文件长时间没有被载入完毕,那下面的HTML也不会被执行,页面不会被渲染而保持空白(HTML页面的渲染是从body标签开始的),这样会影响到用户的使用。因此,现在普遍的做法是将JS文件的外链声明放到body标签的最后面,这样做可以显著地提高页面的显示速度,改善用户体验。

 

2.HTML5script标签中加入了async属性来说明浏览器不需要等待该外链文件下载完毕才去执行下面的语句。而是在整个html文件加载完毕后才去执行其中的代码。该JS文件中的代码最好不要与其它外链文件存在依赖关系,因为html加载完毕外执行该类文件是不会按照它们在html文件中出现的顺序来执行的。

 

3.使用外链JS文件的好处:1.便于维护,你不用对HTML文件逐个进行修改;2.浏览器通常会对下载下来的JS文件进行缓存,如果该JS文件之前已经被下载过了,那它就不用再被下载了。3.HTMLXHTML中声明外部JS文件的格式都是相同的。

 

书中总结:

    JavaScript is inserted into HTML pages by using the <script> element. This element can be used to embed JavaScript into an HTML page, leaving it inline with the rest of the markup, or to include JavaScript that exists in an external file. The following are key points:

1.To include external JavaScript files, the src attribute must be set to the URL of the file to include, which may be a file on the same server as the containing page or one that exists on a completely different domain.

2.All <script> elements are interpreted in the order in which they occur on the page. The code contained within a <script> element must be completely interpreted before code in the next <script> element can begin so long as defer and async attributes are not used.

3.For nondeferred scripts, the browser must complete interpretation of the code inside a <script> element before it can continue rendering the rest of the page. For this reason, <script> elements are usually included toward the end of the page, after the main content and just before the closing </body> tag.

4.You can defer a scripts execution until after the document has rendered by using the defer attribute. Deferred scripts always execute in the order in which they are specified.

5.You can indicate that a script need not wait for other scripts and also not block the document rendering by using the async attribute. Asynchronous scripts are not guaranteed to execute in the order in which they occur in the page.

    By using the <noscript> element, you can specify that content is to be shown only if scripting support isnt available on the browser. Any content contained in the <noscript> element will not be rendered if scripting is enabled on the browser.

posted on 2013-04-09 22:54  RedHood  阅读(217)  评论(0编辑  收藏  举报