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?

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 that script 2 is downloaded & executed before script 1.

According to http://caniuse.com/#feat=script-async, 94.57% 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, 94.59% of all browsers support this. 94.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 6% of browsers that do not support these attributes while speeding up the other 94%.

解答2

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
  • defer script is executed when the document has finished parsing
  • async defer script falls back to the defer behavior if async is not supported

Such scripts will be executed asynchronously/after document ready, which means you cannot do this:

Where should I put <script> tags in HTML markup?的更多相关文章

  1. JavaScript Madness: Dynamic Script Loading

    Introduction I've developed some pretty seriously Javascript intensive sites, where the sheer quanti ...

  2. [Javascript]2. Improve you speed! Script Execution

    Let's take a closer look at how a browser retrieves and acts on scripts.modern browser can parallel ...

  3. how to use coffee script

    TABLE OF CONTENTS TRY COFFEESCRIPT ANNOTATED SOURCE CoffeeScript is a little language that compiles ...

  4. Java Script 学习笔记 -- Ajax

    AJAX 一 AJAX预备知识:json进阶 1.1 什么是JSON? JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.JSON是用字符串来表示Javas ...

  5. Building Applications with Force.com and VisualForce (DEV401) (二十):Visualforce Pages: Visualforce Componets (Tags)

    Dev401-021:Visualforce Pages: Visualforce Componets (Tags) Module Agenda1.Tag Basics2.Tag Bindings T ...

  6. Building Applications with Force.com and VisualForce(Dev401)(十九):Visualforce Pages: Visualforce Componets (Tags)

    Dev401-020:Visualforce Pages: Visualforce Componets (Tags) Module Agenda1.Tag Basics2.Tag Bindings T ...

  7. Ajax及跨域

    概念 Ajax Ajax,Asynchronous JavaScript and XML,字面意思:异步的 JavaScript 和 XML,是指一种创建交互式网页应用的网页开发技术. 用于异步地去获 ...

  8. jQuery-1.9.1源码分析系列(十六)ajax——jsonp原理

    json jsonp 类型 "json":  把响应的结果当作 JSON 执行,并返回一个JavaScript对象.如果指定的是json,响应结果作为一个对象,在传递给成功处理函数 ...

  9. jQuery的$.ajax

    在介绍JSONP之前,先简单的介绍一些JSON.JSON是JavaScript Object Notation的缩写,是一种轻量的.可读的基于文本的数据交换开放标准.源于JavsScript编程语言中 ...

随机推荐

  1. 数据溢出-varchar类型

    数据溢出一.varchar(65535)1.在charset=latin1,因为有额外的开销,实际只能存65532 CREATE table demo( a ) )charset=latin1 eng ...

  2. kmp(前缀出现次数next应用)

    http://acm.hdu.edu.cn/showproblem.php?pid=3336 Count the string Time Limit: 2000/1000 MS (Java/Other ...

  3. Mac下安装nodejs,然后安装Vue-devtools工具

    一.安装nodejs 1.这一步简单,只要上官网下载下来,直接按照提示安装就可以,mac版本的安装方法很简单. 下载nodejs的官方网址是:  nodejs.org    ,浏览器输入就可以跳转到了 ...

  4. JVM(14)之 类加载机制

    开发十年,就只剩下这套架构体系了! >>>   从本篇博文开始,我们就进入虚拟机类加载机制的学习了.那么什么是类加载呢?当我们写完一个Java类的时候,并不是直接就可以运行的,它还要 ...

  5. c#模板化生成接口

    最近打算做这样一个事情,一个桌面系统项目既可以一体化部署,作为一个软件一个进程部署,也可以把业务服务化部署. 那一般意味着我们要完全写2套东西,一套是直接UI调用业务,一套是Ui调用RPC.这样比较多 ...

  6. javascript:变量声明&&赋值的提升和函数声明&&定义的提升在不同情况下的表现

    console.log(a); //undefined console.log(show); //函数的定义 show();         //aaa123 var a = 1; function ...

  7. 265-Keystone II JESD204B 66AK2L06 评估模块 (现行) XEVMK2LX

    Keystone II JESD204B 66AK2L06 评估模块 (现行) XEVMK2LX 一. 板卡概述The XEVMK 2LX is a full-featured evaluation ...

  8. ssm科普篇

    springMVC执行步骤: 1.用户发送请求到前端控制器,前端控制器根据请求信息来决定选择页面控制器,并将请求委托给它 2.页面控制器收到请求后,进行功能处理,首先需要收集和绑定请求参数到一个对象, ...

  9. mongodb 稀疏索引

    稀疏索引(或者称间隙索引)就是只包含有索引字段的文档的条目,即使索引字段包含一个空值.也就是说间隙索引可以跳过那些索引键不存在的文档.因为他并非包含所有的文档,因此称为稀疏索引.与之相对的非稀疏索引或 ...

  10. java 计算时间差

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date d1 = df.parse(&quo ...