且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我什么时候应该使用内联和外部 Javascript?

更新时间:2023-11-10 20:18:40

在最初发布此答案时(2008 年),规则很简单:所有脚本都应该是外部的.兼顾维护和性能.

At the time this answer was originally posted (2008), the rule was simple: All script should be external. Both for maintenance and performance.

(为什么是性能?因为如果代码是分开的,它更容易被浏览器缓存.)

(Why performance? Because if the code is separate, it can easier be cached by browsers.)

JavaScript 不属于 HTML 代码,如果它包含特殊字符(如 <>)甚至会产生问题.

JavaScript doesn't belong in the HTML code and if it contains special characters (such as <, >) it even creates problems.

如今,网络可扩展性已经发生了变化.由于发出多个 HTTP 请求的延迟,减少请求的数量已成为一个有效的考虑因素.这使得答案更加复杂:在大多数情况下,仍然推荐使用外部 JavaScript.但在某些情况下,尤其是非常小的代码段,将它们内联到网站的 HTML 中是有意义的.

Nowadays, web scalability has changed. Reducing the number of requests has become a valid consideration due to the latency of making multiple HTTP requests. This makes the answer more complex: in most cases, having JavaScript external is still recommended. But for certain cases, especially very small pieces of code, inlining them into the site’s HTML makes sense.