When should I use Inline vs. External Javascript?

2018-12-31 18:59发布

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.

18条回答
心情的温度
2楼-- · 2018-12-31 19:44

Another reason why you should always use external scripts is for easier transition to Content Security Policy (CSP). CSP defaults forbid all inline script, making your site more resistant to XSS attacks.

查看更多
查无此人
3楼-- · 2018-12-31 19:45

During early prototyping keep your code inline for the benefit of fast iteration, but be sure to make it all external by the time you reach production.

I'd even dare to say that if you can't place all your Javascript externally, then you have a bad design under your hands, and you should refactor your data and scripts

查看更多
爱死公子算了
4楼-- · 2018-12-31 19:46

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.

查看更多
深知你不懂我心
5楼-- · 2018-12-31 19:47

Always try to use external Js as inline js is always difficult to maintain.

Moreover, it is professionally required that you use an external js since majority of the developers recommend using js externally.

I myself use external js.

查看更多
其实,你不懂
6楼-- · 2018-12-31 19:49

Google has included load times into it's page ranking measurements, if you inline a lot, it will take longer for the spiders to crawl thru your page, this may be influence your page ranking if you have to much included. in any case different strategies may have influence on your ranking.

查看更多
妖精总统
7楼-- · 2018-12-31 19:50

well I think that you should use inline when making single page websites as scripts will not need to be shared across multiple pages

查看更多
登录 后发表回答