我想知道在性能和易于维护方面,何时应该包含外部脚本或将它们与 html 代码内联编写.
I would like to know when I should include external scripts or write them inline with the html code, in terms of performance and ease of maintenance.
对此的一般做法是什么?
What is the general practice for this?
真实世界场景 - 我有几个需要客户端表单验证的 html 页面.为此,我使用了一个包含在所有这些页面上的 jQuery 插件.但问题是,我是否:
Real-world-scenario - I have several html pages that need client-side form validation. For this I use a jQuery plugin that I include on all these pages. But the question is, do I:
谢谢.
在最初发布此答案时(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.
这篇关于我什么时候应该使用内联和外部 Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!