我应该在哪里放< script> HTML标记中的标记? [英] Where should I put <script> tags in HTML markup?

查看:127
本文介绍了我应该在哪里放< script> HTML标记中的标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将JavaScript嵌入到HTML文档中时,放置< script> 标签和包含JavaScript的适当位置在哪里?我似乎记得,你不应该把它们放在< head> 部分,而是放在< body> 部分也是不好的,因为JavaScript必须在页面完全呈现之前解析(或者类似的东西)。这似乎将< body> 部分的 end 保留为< script> 标签。



因此, 是放置< script> tags?



(此问题引用,其中建议JavaScript函数调用应该从< a> 标签到< script> 标签。我特别使用jQuery,但更一般的答案也是适当的。)
<解决方案


  1. 获取HTML页面(例如index.html)
  2. 开始解析HTML

  3. 解析器遇到引用外部脚本文件的< script> 标记。

  4. 浏览器请求脚本文件。同时,解析器会阻止并解析页面上的其他HTML。

  5. 一段时间后脚本被下载并随后执行。 解析器继续解析HTML文档的其余部分。

第4步导致糟糕的用户体验。您的网站基本上停止加载,直到您下载所有脚本。如果有一件事让用户讨厌等待网站加载。

>任何脚本都可以通过 document.write()或其他DOM操作插入自己的HTML。这意味着解析器必须等待脚本被下载并且在它可以安全地解析文档的其余部分之前执行。毕竟,脚本可以在文档中插入自己的HTML。



然而,大多数javascript开发人员不再操作DOM 文档正在加载。相反,他们会等到文档加载完成后再进行修改。例如:

 <! -  index.html  - > 
< html>
< head>
< title>我的页面< /标题>
< script type =text / javascriptsrc =my-script.js>< / script>
< / head>
< body>
< div id =user-greeting>欢迎回来,用户< / div>
< / body>
< / html>

Javascript:

 < code $ // my-script.js 
document.addEventListener(DOMContentLoaded,function(){
//这个函数在DOM准备就绪时运行,也就是文档已经被解析
document.getElementById(user-greeting)。textContent =欢迎回来,Bart;
});

因为您的浏览器不知道我的script.js不会修改文档,直到它已被下载&解析器停止解析。

过时的推荐



解决这个问题的旧方法是将< body> 底部的code>< script> 标记,因为这可以确保解析器不会被阻止,最终。

这种方法有其自身的问题:浏览器在解析整个文档之前无法开始下载脚本。对于大型脚本和大型网站的大型网站样式表,能够尽快下载脚本对于性能非常重要。如果您的网站在2秒内未加载,用户将转到另一个网站。



在最佳解决方案中,浏览器将尽快下载脚本,同时解析文档的其余部分。



现代方法



今天,浏览器支持异步延迟脚本属性。这些属性告诉浏览器在下载脚本时继续解析是安全的。



异步



 < script type =text / javascriptsrc =path / to / script1.jsasync>< / script> 
< script type =text / javascriptsrc =path / to / script2.jsasync>< / script>

具有async属性的脚本是异步执行的。这意味着该脚本在下载时立即执行,同时不会阻止浏览器。

这意味着脚本2可以下载并运行。在脚本1之前执行。


根据 http: //caniuse.com/#feat=script-async ,所有浏览器中有90%支持此功能。

延期



 < script type =text / javascriptsrc =path / to / script1.jsdefer>< / script> 
< script type =text / javascriptsrc =path / to / script2.jsdefer>< / script>

具有defer属性的脚本按顺序执行(即第一个脚本1,然后是脚本2)。这也不会阻止浏览器。



与异步脚本不同,延迟脚本仅在整个文档被加载后执行。



根据 http://caniuse.com/#feat=script-defer,所有浏览器中有90%支持此功能。 92%支持至少部分。

关于浏览器兼容性的一个重要提示:在某些情况下,IE <= 9可能会按顺序执行延迟脚本。如果您需要支持这些浏览器,请首先阅读


$ b

结论



目前最先进的技术是将脚本放在<头> 标记并使用异步延迟属性。这允许您的脚本尽快下载,而不会阻止您的浏览器。



好处是您的网站仍然可以正确加载20%不支持这些浏览器的浏览器属性,同时加速其他80%。

When embedding JavaScript in an HTML document, where is the proper place to put the <script> tags and included JavaScript? I seem to recall that you are not supposed to place these in the <head> section, but placing at the beginning of the <body> section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the end of the <body> section as a logical place for <script> tags.

So, where is the right place to put the <script> tags?

(This question references this question, in which it was suggested that JavaScript function calls should be moved from <a> tags to <script> tags. I'm specifically using jQuery, but more general answers are also appropriate.)

解决方案

Here's what happens when a browser loads a website with a <script> tag on it:

  1. Fetch the HTML page (e.g. index.html)
  2. Begin parsing the HTML
  3. The parser encounters a <script> tag referencing an external script file.
  4. The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
  5. After some time the script is downloaded and subsequently executed.
  6. The parser continues parsing the rest of the HTML document.

Step 4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.

Why does this even happen?

Any script can insert its own HTML via document.write() or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded & executed before it can safely parse the rest of the document. After all, the script could have inserted its own HTML in the document.

However, most javascript developers no longer manipulate the DOM while the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:

<!-- index.html -->
<html>
    <head>
        <title>My Page</title>
        <script type="text/javascript" src="my-script.js"></script>
    </head>
    <body>
        <div id="user-greeting">Welcome back, user</div>
    </body>
</html>

Javascript:

// my-script.js
document.addEventListener("DOMContentLoaded", function() { 
    // this function runs when the DOM is ready, i.e. when the document has been parsed
    document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});

Because your browser does not know my-script.js isn't going to modify the document until it has been downloaded & executed, the parser stops parsing.

Antiquated recommendation

The old approach to solving this problem was to put <script> tags at the bottom of your <body>, because this ensures the parser isn't blocked until the very end.

This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts & stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.

In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.

The modern approach

Today, browsers support the async and defer attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.

async

<script type="text/javascript" src="path/to/script1.js" async></script>
<script type="text/javascript" src="path/to/script2.js" async></script>

Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible to script 2 is downloaded & executed before script 1.

According to http://caniuse.com/#feat=script-async, 90% of all browsers support this.

defer

<script type="text/javascript" src="path/to/script1.js" defer></script>
<script type="text/javascript" src="path/to/script2.js" defer></script>

Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.

Unlike async scripts, defer scripts are only executed after the entire document has been loaded.

According to http://caniuse.com/#feat=script-defer, 90% of all browsers support this. 92% support it at least partially.

An important note on browser compatibility: in some circumstances IE <= 9 may execute deferred scripts out of order. If you need to support those browsers, please read this first!

Conclusion

The current state-of-the-art is to put scripts in the <head> tag and use the async or defer attributes. This allows your scripts to be downloaded asap without blocking your browser.

The good thing is that your website should still load correctly on the 20% of browsers that do not support these attributes while speeding up the other 80%.

这篇关于我应该在哪里放&lt; script&gt; HTML标记中的标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆