[英]Best practice to optimize javascript loading
I have read a few articles online about optimizing javascript loading. 我在网上阅读了一些关于优化javascript加载的文章。 A few key points I got is to minimize the number of script files (http requests), minify and enable gzip on the server. 我得到的几个关键点是最小化脚本文件(http请求)的数量,缩小和启用服务器上的gzip。 Currently, what is done on my side is that all javascript files are minified, and gzip can be simply enabled as well. 目前,我所做的是所有javascript文件都缩小了,gzip也可以简单地启用。
Part 1) 第1部分)
My problem is that I have around 20 javascript files, there is one common.js that has all the core functions. 我的问题是我有大约20个javascript文件,有一个common.js具有所有核心功能。 Besides that, every page would load at least one other file that implements the functionality of that page. 除此之外,每个页面都会加载至少一个实现该页面功能的其他文件。
Solution 1, is to combine all scripts in one big script file, and get loaded once for each client, which seems to be what everyone else is doing. 解决方案1是将所有脚本组合在一个大脚本文件中,并为每个客户端加载一次,这似乎是其他人正在做的事情。 I guess YUI or JSMin can be used for compressing, so I should combine the files manually? 我猜YUI或JSMin可以用于压缩,所以我应该手动组合文件?
Solution 2, lazy loading when a required function is needed, I don't really know how this works, but it seems to be a way to do it, though still requires more http requests. 解决方案2,当需要一个必需的函数时,延迟加载,我真的不知道它是如何工作的,但它似乎是一种方法,但仍然需要更多的http请求。 I would love to hear any inputs for this. 我很想听到有关此的任何意见。
Part 2) 第2部分)
The web application I am working on will be deployed to many other computers, since javascripts are pretty small, is it a good practice to make a script that dynamically load the newest script from a central server, so that every client will run the newest script? 我正在处理的Web应用程序将部署到许多其他计算机,因为javascripts非常小,制作一个从中央服务器动态加载最新脚本的脚本是一个好习惯,这样每个客户端都将运行最新的脚本?
General best practice is considered to be 一般最佳实践被认为是
Merge into as few files as possible 合并为尽可能少的文件
Minify 缩小
Serve gzipped 服务gzipped
Serve as late as possible (some may need to be in the head, but generally before or asynchronously is preferred 服务尽可能晚(有些可能需要在头部,但通常在优先之前或异步
This is general advice, you need to do it and test to ensure it's right for your case. 这是一般建议,您需要进行测试以确保它适合您的情况。
Minimising HTTP requests is important, latency is a performance killer... 最小化HTTP请求很重要,延迟是性能杀手......
Part 1: Like you said, there's two approaches. 第1部分:像你说的那样,有两种方法。
Part 2: 第2部分:
You have to break optimisation into several steps 您必须将优化分为几个步骤
<script src='//...' async defer>
when possible, if you have script dependencies, be careful when using asycn loading. 尽可能使用<script src='//...' async defer>
,如果你有脚本依赖,在使用asycn加载时要小心。 If you use AMD module, it will make sure your dependent modules are loaded in advance, and they only load once per page refresh. 如果您使用AMD模块,它将确保您的相关模块提前加载,并且每页刷新只加载一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.