在JavaScript中嵌入JavaScript或在外部保存JavaScript有哪些优点和缺点? [英] What are some advantages and disadvantages for embedding JavaScript in HTML or saving it externally?

查看:138
本文介绍了在JavaScript中嵌入JavaScript或在外部保存JavaScript有哪些优点和缺点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找简单的要点答案。我试过看了一遍,谷歌搜索,其他问题在这里,但我永远找不到每种方法的优点和缺点。

I'm looking for simple bullet point answers please. I've tried looking all over, Googling, other questions here but I can never find both advantages and disadvantages for each method.

推荐答案

这是我从 W3Schools 获得的与外部javascript文件有关的答案

This is the answer I got from W3Schools pertaining to external javascript files


  • 它允许分离关注点 - 其中在简单的页面中并不是一件大事,但随着脚本变得越来越大,你可以拥有一个单一的html页面。一般来说,大文件不是维护的理想选择

  • It allows separation of concerns - which is not a big deal in simple pages but as the script grows larger you can have a monolithic html page. Big files in general are not ideal for maintainability

它允许缓存 - 当浏览器从外部加载脚本时(无论是从哪里来的)您的网站或cdn)它会缓存该文件以供将来使用。这就是为什么cdn是常用脚本的首选。使浏览器使用缓存脚本,而不是每次加载页面时都构建一个新脚本,这会使页面加载更快

It allows caching - when the browser loads a script externally (whether it's be from your site or a cdn) it caches the file for future use. That's why cdn's are preferred for commonly used scripts. Makes the browser use a cached script instead of building a new one every time the page loads which makes the page load faster

更可读的代码 - 这与第一个要点有关,但重要的是它。我们人类使用的文件越小越好。更容易发现错误,更容易将火炬传递给下一个从事项目工作的开发人员或从中学习。

More readable code - this ties into the first bullet point but nevertheless it is important. The smaller the files we humans are working with the better. It is easier to catch mistakes and much easier to pass of the torch to the next developer working on the project or learning from it.


  • 浏览器必须发出http请求以获取代码

可能还有其他浏览器特定原因,但我相信主要原因是将代码分成不同的组件。

There may be other browser specific reasons as well, but I believe the main reason is the separation of code into different components.

这篇关于在JavaScript中嵌入JavaScript或在外部保存JavaScript有哪些优点和缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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