【问题标题】:Best way to call an external js file from the HTML page (as of July 2017)从 HTML 页面调用外部 js 文件的最佳方式(截至 2017 年 7 月)
【发布时间】:2017-07-16 23:31:29
【问题描述】:

截至 2017 年 7 月,从 HTML 页面调用外部 Javascript 文件的最佳做法是什么?

1) 在带有 DEFER 属性的 HEAD 中:

<head>
    <title></title>
    <script src="script.js" defer></script>
</head>

2) 在没有 DEFER 属性的 HEAD 中,将所有 js 代码放在一个函数中,该函数在 DOM 加载后触发。

<head>
    <title></title>
    <script src="script.js"></script>
</head>

script.js 文件:

function init() {
    // all JS code in here
}
window.onload = init;

3) 紧接在结束 BODY 标记之前:

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

4) 紧接在结束 BODY 标记之后:

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

5) 其他方式?

【问题讨论】:

    标签: javascript html external


    【解决方案1】:

    调用外部 javascript 的最佳方式是 &lt;script type="text/javascript" src="script.js" async&gt;&lt;/script&gt; 在正文的结束标记之前 (&lt;/body&gt;)。

    async 允许 DOM 在找到 &lt;script&gt; 标记时不停止其进程。

    更多信息请参考这篇帖子https://developers.google.com/speed/docs/insights/BlockingJS

    【讨论】:

    • 你有可以支持这个的来源或文档吗?
    • @hwdbc 是的,我有文档。几天前,我通过了 Google 移动网站认证。这是考试的一部分。 developers.google.com/speed/docs/insights/BlockingJS
    • 感谢您提供。我之所以问,是因为 OP 能够访问良好的文档会有所帮助。
    • @hwdbc 有道理。
    • 感谢您的信息。如果您有很大一部分用户使用“旧”版本的 Internet Explorer,您还会推荐这种方法吗?大约一年半前,我的庞大用户群切换到 IE11(从 IE8)。估计还有很多用户没有升级到IE11。
    猜你喜欢
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2013-10-09
    • 2012-07-26
    • 1970-01-01
    • 2011-11-10
    相关资源
    最近更新 更多