什么时候应该使用内联与外部Javascript? [英] When should I use Inline vs. External Javascript?

查看:98
本文介绍了什么时候应该使用内联与外部Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想知道何时应该包含外部脚本或将它们与html代码内联编写在一起。

什么是一般的做法是什么?



真实世界场景 - 我有几个需要客户端表单验证的html页面。为此,我使用了包含在所有这些页面上的jQuery插件。但问题是,我是否:


  • 写入配置此脚本内嵌的代码位

  • 在所有这些html页面之间包含一个文件中的所有位?

  • 将每个位包含在单独的外部文件中,每个html页面一个?


谢谢。

解决方案

(2008),规则很简单:所有脚本都应该是外部的。为了维护和性能。



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

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



现在,网络可伸缩性已经发生了变化。由于发出多个HTTP请求的延迟,减少请求数已成为一个有效的考虑因素。这使得答案更复杂:在大多数情况下,建议使用JavaScript外部仍然。但是对于某些情况,特别是非常小的代码,将它们内联到网站的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?

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:

  • write the bits of code that configure this script inline?
  • include all bits in one file that's share among all these html pages?
  • include each bit in a separate external file, one for each html page?

Thanks.

解决方案

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 doesn't belong in the HTML code and if it contains special characters (such as <, >) it even creates problems.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆