简体   繁体   English

我应该放在哪里<script> tags in HTML markup?

[英]Where should I put <script> tags in HTML markup?

When embedding JavaScript in an HTML document, where is the proper place to put the <script> tags and included JavaScript?在 HTML 文档中嵌入 JavaScript 时,放置<script>标记和包含 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).我似乎记得您不应该将它们放在<head>部分中,但是放在<body>部分的开头也很糟糕,因为必须在页面完全呈现之前解析 JavaScript(或类似的东西)。 This seems to leave the end of the <body> section as a logical place for <script> tags.这似乎将<body>部分的末尾作为<script>标签的逻辑位置。

So, where is the right place to put the <script> tags?那么,放置<script>标签正确位置在哪里?

(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.) (这个问题引用了这个问题,其中建议 JavaScript 函数调用应该从<a>标记移动到<script>标记。我专门使用 jQuery,但更一般的答案也是合适的。)

Here's what happens when a browser loads a website with a <script> tag on it:当浏览器加载带有<script>标签的网站时,会发生以下情况:

  1. Fetch the HTML page (eg index.html )获取 HTML 页面(例如index.html
  2. Begin parsing the HTML开始解析 HTML
  3. The parser encounters a <script> tag referencing an external script file.解析器遇到引用外部脚本文件的<script>标记。
  4. The browser requests the script file.浏览器请求脚本文件。 Meanwhile, the parser blocks and stops parsing the other HTML on your page.同时,解析器会阻止并停止解析页面上的其他 HTML。
  5. After some time the script is downloaded and subsequently executed.一段时间后,脚本被下载并随后执行。
  6. The parser continues parsing the rest of the HTML document.解析器继续解析 HTML 文档的其余部分。

Step #4 causes a bad user experience.第 4 步会导致糟糕的用户体验。 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.任何脚本都可以通过document.write()或其他 DOM 操作插入自己的 HTML。 This implies that the parser has to wait until the script has been downloaded and executed before it can safely parse the rest of the document.这意味着解析器必须等到脚本下载并执行后才能安全地解析文档的其余部分。 After all, the script could have inserted its own HTML in the document.毕竟,脚本可以在文档中插入自己的 HTML。

However, most JavaScript developers no longer manipulate the DOM while the document is loading.但是,大多数 JavaScript 开发人员不再文档加载时操作 DOM。 Instead, they wait until the document has been loaded before modifying it.相反,他们会等到文档加载完毕后再进行修改。 For example:例如:

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

JavaScript: 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 and executed, the parser stops parsing.因为您的浏览器不知道my-script.js在下载并执行之前不会修改文档,因此解析器停止解析。

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.解决这个问题的旧方法是将<script>标签放在<body>的底部,因为这样可以确保解析器直到最后都不会被阻塞。

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 and 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.如果您的网站在 2 秒内未加载,人们将转到另一个网站。

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.今天,浏览器支持脚本的asyncdefer属性。 These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.这些属性告诉浏览器在下载脚本时继续解析是安全的。

async异步

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

Scripts with the async attribute are executed asynchronously.具有 async 属性的脚本是异步执行的。 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 that script 2 is downloaded and executed before script 1.这意味着脚本 2 可能在脚本 1 之前下载并执行。

According to http://caniuse.com/#feat=script-async , 97.78% of all browsers support this.根据http://caniuse.com/#feat=script-async ,97.78% 的浏览器都支持这一点。

defer推迟

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

Scripts with the defer attribute are executed in order (ie first script 1, then script 2).具有 defer 属性的脚本按顺序执行(即首先执行脚本 1,然后执行脚本 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 , 97.79% of all browsers support this.根据http://caniuse.com/#feat=script-defer ,97.79% 的浏览器都支持这一点。 98.06% support it at least partially. 98.06% 至少部分支持它。

An important note on browser compatibility: in some circumstances, Internet Explorer 9 and earlier may execute deferred scripts out of order.关于浏览器兼容性的重要说明:在某些情况下,Internet Explorer 9 和更早版本可能会乱序执行延迟脚本。 If you need to support those browsers, please read this first!如果您需要支持这些浏览器,请先阅读内容!

(To learn more and see some really helpful visual representations of the differences between async, defer and normal scripts check the first two links at the references section of this answer) (要了解更多信息并查看异步、延迟和普通脚本之间差异的一些非常有用的视觉表示,请查看此答案的参考部分的前两个链接)

Conclusion结论

The current state-of-the-art is to put scripts in the <head> tag and use the async or defer attributes.当前的最新技术是将脚本放在<head>标记中并使用asyncdefer属性。 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 2% of browsers that do not support these attributes while speeding up the other 98%.好消息是您的网站仍应在 2% 的不支持这些属性的浏览器上正确加载,同时加快其他 98% 的速度。

References参考

Just before the closing body tag, as stated onPut Scripts at the Bottom :就在结束正文标记之前,如将脚本放在底部所述

Put Scripts at the Bottom将脚本放在底部

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. HTTP/1.1 规范建议浏览器每个主机名并行下载不超过两个组件。 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.但是,在下载脚本时,浏览器不会启动任何其他下载,即使在不同的主机名上也是如此。

Non-blocking script tags can be placed just about anywhere:非阻塞脚本标签几乎可以放置在任何地方:

<script src="script.js" async></script>
<script src="script.js" defer></script>
<script src="script.js" async defer></script>
  • async script will be executed asynchronously as soon as it is available async脚本将在可用时立即异步执行
  • defer script is executed when the document has finished parsing当文档完成解析时执行defer脚本
  • async defer script falls back to the defer behavior if async is not supported如果不支持异步,则async defer脚本回退到延迟行为

Such scripts will be executed asynchronously/after document ready, which means you cannot do this:此类脚本将在文档准备好后异步执行,这意味着您不能这样做:

<script src="jquery.js" async></script>
<script>jQuery(something);</script>
<!--
  * might throw "jQuery is not defined" error
  * defer will not work either
-->

Or this:或这个:

<script src="document.write(something).js" async></script>
<!--
  * might issue "cannot write into document from an asynchronous script" warning
  * defer will not work either
-->

Or this:或这个:

<script src="jquery.js" async></script>
<script src="jQuery(something).js" async></script>
<!--
  * might throw "jQuery is not defined" error (no guarantee which script runs first)
  * defer will work in sane browsers
-->

Or this:或这个:

<script src="document.getElementById(header).js" async></script>
<div id="header"></div>
<!--
  * might not locate #header (script could fire before parser looks at the next line)
  * defer will work in sane browsers
-->

Having said that, asynchronous scripts offer these advantages:话虽如此,异步脚本具有以下优点:

  • Parallel download of resources :并行下载资源
    Browser can download stylesheets, images and other scripts in parallel without waiting for a script to download and execute.浏览器可以并行下载样式表、图像和其他脚本,而无需等待脚本下载和执行。
  • Source order independence :源顺序独立
    You can place the scripts inside head or body without worrying about blocking (useful if you are using a CMS).您可以将脚本放在 head 或 body 中,而不必担心阻塞(如果您使用 CMS,则很有用)。 Execution order still matters though.执行顺序仍然很重要。

It is possible to circumvent the execution order issues by using external scripts that support callbacks.可以通过使用支持回调的外部脚本来规避执行顺序问题。 Many third party JavaScript APIs now support non-blocking execution.许多第三方 JavaScript API 现在支持非阻塞执行。 Here is an example of loading the Google Maps API asynchronously .这是一个异步加载 Google Maps API的示例。

The standard advice, promoted by the Yahoo!雅虎推广的标准建议! Exceptional Performance team, is to put the <script> tags at the end of the document body so they don't block rendering of the page. Exceptional Performance 团队将<script>标签放在文档正文的末尾,这样它们就不会阻塞页面的呈现。

But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:但是有一些更新的方法可以提供更好的性能,如this answer about the load time of the Google Analytics JavaScript file中所述:

There are some great slides by Steve Souders (client-side performance expert) about: Steve Souders(客户端性能专家)有一些很棒的幻灯片,内容是:

  • Different techniques to load external JavaScript files in parallel并行加载外部 JavaScript 文件的不同技术
  • their effect on loading time and page rendering它们对加载时间和页面渲染的影响
  • what kind of "in progress" indicators the browser displays (eg 'loading' in the status bar, hourglass mouse cursor).浏览器显示什么样的“进行中”指示器(例如状态栏中的“加载”、沙漏鼠标光标)。

The modern approach in 2019 is using ES6 module type scripts . 2019 年的现代方法是使用 ES6 模块类型脚本

<script type="module" src="..."></script>

By default, modules are loaded asynchronously and deferred.默认情况下,模块是异步加载和延迟加载的。 ie you can place them anywhere and they will load in parallel and execute when the page finishes loading.即,您可以将它们放在任何地方,它们将并行加载并在页面完成加载时执行。

The differences between a script and a module are described here:这里描述了脚本和模块之间的区别:

Classic scripts vs. module scripts in JavaScript JavaScript 中的经典脚本与模块脚本

The execution of a module compared to a script is described here:与脚本相比,模块的执行如下所述:

Modules are deferred by default 模块默认延迟

Support is shown here:此处显示支持:

Can I use... Support tables for HTML5, CSS3, etc我可以使用... HTML5、CSS3 等的支持表

If you are using jQuery then put the JavaScript code wherever you find it best and use $(document).ready() to ensure that things are loaded properly before executing any functions.如果您使用 jQuery,则将 JavaScript 代码放在您认为最好的地方,并使用$(document).ready()确保在执行任何函数之前正确加载内容。

On a side note: I like all my script tags in the <head> section as that seems to be the cleanest place.附带说明:我喜欢<head>部分中的所有脚本标签,因为那似乎是最干净的地方。

    <script src="myjs.js"></script>
</body>

The script tag should always be used before the body close or at the bottom in HTML file.脚本标签应始终在正文关闭之前或HTML 文件的底部使用

The Page will load with HTML and CSS and later JavaScript will load.页面将加载 HTML 和 CSS,稍后将加载 JavaScript。

Check this if required:如果需要,请检查:

http://stevesouders.com/hpws/rule-js-bottom.php http://stevesouders.com/hpws/rule-js-bottom.php

The best place to put <script> tag is before closing </body> tag, so the downloading and executing it doesn't block the browser to parse the HTML in document,放置<script>标签的最佳位置是在关闭</body>标签之前,因此下载和执行它不会阻止浏览器解析文档中的 HTML,

Also loading the JavaScript files externally has its own advantages like it will be cached by browsers and can speed up page load times, it separates the HTML and JavaScript code and help to manage the code base better.此外,从外部加载 JavaScript 文件也有其自身的优势,例如它会被浏览器缓存并可以加快页面加载时间,它将 HTML 和 JavaScript 代码分开,有助于更好地管理代码库。

But modern browsers also support some other optimal ways, like async and defer to load external JavaScript files.但现代浏览器也支持其他一些优化方式,比如asyncdefer加载外部 JavaScript 文件。

Async and Defer异步和延迟

Normally HTML page execution starts line by line.通常 HTML 页面执行是逐行开始的。 When an external JavaScript <script> element is encountered, HTML parsing is stopped until a JavaScript is download and ready for execution.当遇到外部 JavaScript <script>元素时,HTML 解析将停止,直到 JavaScript 下载并准备好执行。 This normal page execution can be changed using the defer and async attribute.可以使用deferasync属性更改此正常页面执行。

Defer

When a defer attribute is used, JavaScript is downloaded parallelly with HTML parsing, but it will be execute only after full HTML parsing is done.当使用 defer 属性时,JavaScript 会与 HTML 解析并行下载,但只有在完成完整的 HTML 解析后才会执行。

<script src="/local-js-path/myScript.js" defer></script>

Async

When the async attribute is used, JavaScript is downloaded as soon as the script is encountered and after the download, it will be executed asynchronously (parallelly) along with HTML parsing.当使用 async 属性时,一旦遇到脚本就会下载 JavaScript,下载后,它将与 HTML 解析一起异步(并行)执行。

<script src="/local-js-path/myScript.js" async></script>

When to use which attributes何时使用哪些属性

  • If your script is independent of other scripts and is modular, use async .如果您的脚本独立于其他脚本并且是模块化的,请使用async
  • If you are loading script1 and script2 with async , both will run parallelly along with HTML parsing, as soon as they are downloaded and available.如果您使用async加载 script1 和 script2 ,一旦下载并可用,两者将与 HTML 解析一起并行运行。
  • If your script depends on another script then use defer for both:如果您的脚本依赖于另一个脚本,则对两者都使用defer
  • When script1 and script2 are loaded in that order with defer , then script1 is guaranteed to execute first,当 script1 和 script2 以defer的顺序加载时, script1 保证首先执行,
  • Then script2 will execute after script1 is fully executed.然后 script2 将在 script1 完全执行后执行。
  • Must do this if script2 depends on script1.如果 script2 依赖于 script1,则必须这样做。
  • If your script is small enough and is depended by another script of type async then use your script with no attributes and place it above all the async scripts.如果您的脚本足够小并且依赖于另一个async类型的脚本,那么请使用不带属性的脚本并将其放在所有async脚本之上。

Reference: External JavaScript JS File – Advantages, Disadvantages, Syntax, Attributes参考: 外部 JavaScript JS 文件 – 优点、缺点、语法、属性

It turns out it can be everywhere.事实证明它可以无处不在。

You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).您可以使用 jQuery 之类的东西来推迟执行,因此它的放置位置无关紧要(解析期间的性能小幅下降除外)。

The most conservative (and widely accepted) answer is "at the bottom just before the ending tag", because then the entire DOM will have been loaded before anything can start executing.最保守(并且被广泛接受)的答案是“在结束标记之前的底部”,因为这样整个 DOM 将在任何东西可以开始执行之前被加载。

There are dissenters, for various reasons, starting with the available practice to intentionally begin execution with a page onload event.出于各种原因,有一些反对者从可用的做法开始,即故意从页面加载事件开始执行。

It depends.这取决于。 If you are loading a script that's necessary to style your page / using actions in your page (like click of a button) then you better place it at the top.如果您正在加载一个需要设置页面样式/使用页面中的操作(例如单击按钮)的脚本,那么您最好将其放在顶部。 If your styling is 100% CSS and you have all fallback options for the button actions then you can place it at the bottom.如果你的样式是 100% CSS 并且你有按钮动作的所有后备选项,那么你可以把它放在底部。

Or the best thing (if that's not a concern) is you can make a modal loading box, place your JavaScript code at the bottom of your page and make it disappear when the last line of your script gets loaded.或者最好的事情(如果这不是问题的话)是您可以制作一个模式加载框,将您的 JavaScript 代码放在页面底部,并在加载脚本的最后一行时使其消失。 This way you can avoid users using actions in your page before the scripts are loaded.这样,您可以避免用户在加载脚本之前在您的页面中使用操作。 And also avoid the improper styling.并且还要避免不恰当的造型。

Including scripts at the end is mainly used where the content/ styles of the web page is to be shown first.最后包含脚本主要用于首先显示网页的内容/样式的地方。

Including the scripts in the head loads the scripts early and can be used before the loading of the whole web page.在头部包含脚本会提前加载脚本,并且可以在加载整个网页之前使用。

If the scripts are entered at last the validation will happen only after the loading of the entire styles and design which is not appreciated for fast responsive websites.如果最后输入脚本,则只有在加载整个样式和设计后才会进行验证,这对于快速响应的网站来说是不受欢迎的。

Script blocks DOM load until it's loaded and executed.脚本会阻止 DOM 加载,直到它被加载并执行。

If you place scripts at the end of <body> , all of the DOM has a chance to load and render (the page will "display" faster).如果将脚本放在<body>的末尾,则所有 DOM 都有机会加载和呈现(页面将“显示”得更快)。 <script> will have access to all of those DOM elements. <script>将有权访问所有这些 DOM 元素。

On the other hand, placing it after the <body> start or above will execute the script (where there still aren't any DOM elements).另一方面,将它放在<body>开始或以上将执行脚本(仍然没有任何 DOM 元素)。

You are including jQuery which means you can place it wherever you wish and use .ready() .您正在包含 jQuery,这意味着您可以将它放置在您希望的任何位置并使用.ready()

  • If you still care a lot about support and performance in Internet Explorer before version 10 , it's best to always make your script tags the last tags of your HTML body.如果您仍然非常关心版本 10之前的 Internet Explorer 的支持和性能,那么最好始终将您的脚本标签作为 HTML 正文的最后一个标签。 That way, you're certain that the rest of the DOM has been loaded and you won't block and rendering.这样,您就可以确定 DOM 的其余部分已被加载,并且您不会阻塞和渲染。

  • If you don't care too much any more about in Internet Explorer before version 10, you might want to put your scripts in the head of your document and use defer to ensure they only run after your DOM has been loaded ( <script type="text/javascript" src="path/to/script1.js" defer></script> ).如果您不再关心 10 版之前的 Internet Explorer,您可能希望将脚本放在文档的头部并使用defer确保它们仅在您的 DOM 加载后运行( <script type="text/javascript" src="path/to/script1.js" defer></script> )。 If you still want your code to work in Internet Explorer before version 10, don't forget to wrap your code in a window.onload even, though!如果您仍然希望您的代码在 10 版之前的 Internet Explorer 中工作,请不要忘记将您的代码包装在window.onload中,尽管如此!

You can place most of <script> references at the end of <body> .您可以将大部分<script>引用放在<body>的末尾。

But if there are active components on your page which are using external scripts, then their dependency (.js files) should come before that (ideally in the head tag).但是,如果您的页面上有使用外部脚本的活动组件,那么它们的依赖项(.js 文件)应该在此之前(最好在head标签中)。

Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.根据脚本及其使用情况,最好的可能(就页面加载和渲染时间而言)可能是不使用传统的 <script>-tag 本身,而是异步地动态触发脚本的加载。

There are some different techniques, but the most straightforward is to use document.createElement("script") when the window.onload event is triggered.有一些不同的技术,但最直接的方法是在触发 window.onload 事件时使用 document.createElement("script")。 Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.然后在页面本身呈现时首先加载脚本,因此不会影响用户必须等待页面出现的时间。

This naturally requires that the script itself is not needed for the rendering of the page.这自然要求页面的渲染不需要脚本本身。

For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow , but now at Google).有关更多信息,请参阅 Steve Souders( YSlow的创建者,但现在在 Google)的文章耦合异步脚本

The best place to write your JavaScript code is at the end of the document after or right before the </body> tag to load the document first and then execute the JavaScript code.编写 JavaScript 代码的最佳位置是在</body>标记之后或之前的文档末尾,以首先加载文档,然后执行 JavaScript 代码。

<script> ... your code here ... </script>
</body>

And if you write in jQuery , the following can be in the head document and it will execute after the document loads:如果您使用jQuery编写,则可以在头文档中执行以下操作,并在文档加载后执行:

<script>
    $(document).ready(function(){
        // Your code here...
    });
</script>

You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code.您可以通过使用包裹 JavaScript 代码的专用 HTML 标签<script>在 HTML 文档中添加 JavaScript 代码。

The <script> tag can be placed in the <head> section of your HTML, in the <body> section, or after the </body> close tag, depending on when you want the JavaScript to load. <script>标签可以放置在 HTML 的<head>部分、 <body>部分或</body>关闭标签之后,具体取决于您希望何时加载 JavaScript。

Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.通常,JavaScript 代码可以进入文档<head>部分,以保持它们包含在 HTML 文档的主要内容之外。

However, if your script needs to run at a certain point within a page's layout — like when using document.write to generate content — you should put it at the point where it should be called, usually within the <body> section.但是,如果您的脚本需要在页面布局中的某个点运行(例如使用document.write生成内容时),您应该将它放在应该调用它的位置,通常是在<body>部分中。

I think it depends on the webpage execution.我认为这取决于网页执行。

If the page that you want to display can not displayed properly without loading JavaScript first then you should include the JavaScript file first.如果您要显示的页面在不先加载 JavaScript 的情况下无法正常显示,那么您应该首先包含 JavaScript 文件。

But if you can display/render a webpage without initially download JavaScript file, then you should put JavaScript code at the bottom of the page.但是,如果您可以在不下载 JavaScript 文件的情况下显示/呈现网页,那么您应该将 JavaScript 代码放在页面底部。 Because it will emulate a speedy page load, and from a user's point of view, it would seems like that the page is loading faster.因为它将模拟快速页面加载,并且从用户的角度来看,页面加载速度似乎更快。

为了防止和UI阻塞,在body标记之前结束。

Always, we have to put scripts before the closing body tag expect some specific scenario.总是,我们必须在结束正文标记之前放置脚本,以期待一些特定的场景。

For Example :例如 :

`<html> <body> <script> document.getElementById("demo").innerHTML = "Hello JavaScript!"; </script> </body> </html>`

Prefer to put it before the </body> closing tag.最好把它放在</body>结束标记之前。

Why?为什么? As per the official doc: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics#a_hello_world!_example根据官方文档: https ://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics#a_hello_world!_example

Note: The reason the instructions (above) place the element near the bottom of the HTML file is that the browser reads code in the order it appears in the file.注意:说明(上面)将元素放置在 HTML 文件底部附近的原因是浏览器按照代码在文件中出现的顺序读取代码。

If the JavaScript loads first and it is supposed to affect the HTML that hasn't loaded yet, there could be problems.如果 JavaScript 先加载并且它应该影响尚未加载的 HTML,则可能会出现问题。 Placing JavaScript near the bottom of an HTML page is one way to accommodate this dependency.将 JavaScript 放置在 HTML 页面的底部附近是适应这种依赖性的一种方法。 To learn more about alternative approaches, see Script loading strategies.要了解有关替代方法的更多信息,请参阅脚本加载策略。

It makes more sense to me to include the script after the HTML.在 HTML 之后包含脚本对我来说更有意义。 Because most of the time I need the Dom to load before I execute my script.因为大多数时候我需要在执行脚本之前加载 Dom。 I could put it in the head tag but I don't like all the Document loading listener overhead.我可以把它放在 head 标签中,但我不喜欢所有的 Document 加载侦听器开销。 I want my code to be short and sweet and easy to read.我希望我的代码短小精悍,易于阅读。

I've heard old versions of safari was quarky when adding your script outside of the head tag but I say who cares.我听说在 head 标签之外添加脚本时,旧版本的 safari 很古怪,但我说谁在乎。 I don't know anybody using that old crap do you.我不知道有人在用那个老废话吗?

Good question by the way.顺便问一下好问题。

At The End of HTML Document 在HTML文档的末尾

So that it will not effect the loading of the HTML document in the browser at the time of execution. 因此,在执行时不会影响将HTML文档加载到浏览器中。

Script in JavaScript: JavaScript 中的脚本:

REGULAR VS.常规 VS。 ASYNC VS.异步 VS。 DEFER推迟

在此处输入图片说明

在此处输入图片说明

You can place where you want the scripts and one is not better than another practice. 您可以将脚本放在需要的地方,一个脚本并不比另一种更好。

the situation is as follows: 情况如下:

The page load linearly, "top-down", so if you put the script in the head ensures that it starts to load before everything, now, if you put it inside the body mixed with the code can cause page loads a unsightly manner. 页面是线性加载的,“自上而下”,因此,如果将脚本放在头部,可以确保它在所有内容之前都开始加载,现在,如果将其放入与代码混合的正文中,则可能导致页面加载难看。

identify good practice does not depend on where. 确定良好实践并不取决于在哪里。

to support you, I will mention the following: 为了支持您,我将提及以下内容:

you can place: 您可以放置​​:

and the page will load linearly 并且页面将线性加载

page is loaded asynchronously with other content 页面与其他内容异步加载

the content of the page will load before and after completion of loading the scripts are loaded 页面的内容将在加载完成之前和之后加载

good practice here would be, when will implement each? 好的做法是,什么时候实施?

I hope I've been helpful, anything just answer me this issue. 我希望我能有所帮助,任何事情都可以回答我这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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