与在构建过程中连接脚本文件相比,使用脚本加载器有什么优势?
我听说过很多关于脚本加载器的信息,比如 RequireJS。与在构建过程中连接源文件相比,使用脚本加载器有什么优势?
I've been hearing a lot about script loaders such as RequireJS. What's the advantage of using a script loader over concatenating your source files in a build process?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在构建过程中连接源文件的优点是客户端必须发出更少的请求,并且请求开销减少,页面加载时间减少,使其更快
例如。假设你有 10 个 javascript 文件,现在浏览器必须发出 10 个
HTTP
请求,并且每个请求都有自己的开销(请求和响应标头),现在如果你将这 10 个文件连接到 2 或 3 个,则只有 2 个或 3 个 HTTP 请求,从而减少开销。此外,任何遵循 HTTP 1.1 规范的客户端都不允许同时连接到单个域超过 2 个,因此您会明白为什么减少连接(请求)很重要,而脚本加载器用于加载 javascript -需求,这意味着假设您只需要一些 javascript,如果用户在特定文本框中键入,那么您不会在页面加载时请求该 javascript,而是仅在需要时加载它(用户在文本框中键入)。
例如,当您在 facebook 上标记照片时,加载照片页面时标记所需的 javascipt 不可用,但在您尝试标记照片时会请求该 javascipt
Concatenating your source files in the build process has the advantage that you the client has to make fewer requests and the request overhead is reduced and page load time decreases making it faster
eg. suppose you have 10 javascript files now the browser has to make 10
HTTP
requests and each request has its own overhead(request and response headers) now if you concatenate those 10 files to 2 or 3 there are just 2 or 3HTTP
requests thus reducing the overhead. also any client which followsHTTP 1.1
specification does not allow more than 2 simultaneous connections to a single domain so you see why its important to have less connections(requests)whereas script loaders are used to load javascript on-demand,it means that suppose you are only going to need some javascript if the user types in a particular text box then you dont request that javascript on page load but only load it when it is in demand(user types in the text box).
eg when you tag photos on facebook the javascipt needed for tagging is not available when the photos page loads but its requested when you try to tag the photos
脚本加载器对于避免在您可能不需要全部 JavaScript 文件的情况下加载大量 JavaScript 文件很有用:假设一个页面仅使用 50 个可用模块中的 2 个,那么您可以使用脚本加载器仅获取您关心的部分,而不是获取全部 50 个。这可以加快页面加载时间并降低带宽成本。
Script loaders are useful to avoid having to load large volumes of JavaScript files in situations where you might not need all of it: say a page is only using 2 out of the 50 modules available, then you can use a script loader to only get the pieces you care about rather than fetching all 50. This speeds your page load time and reduces your bandwidth costs.