网站优化初学者指南 (#3473)

* translation

* 网站优化初学者指南

网站优化初学者指南

* Update a-beginners-guide-to-website-optimization.md

* Update a-beginners-guide-to-website-optimization.md

* Update a-beginners-guide-to-website-optimization.md

* Update a-beginners-guide-to-website-optimization.md
This commit is contained in:
Starrier
2018-03-21 09:52:54 +08:00
committed by LeviDing
parent 8172e6d49c
commit 7fb1abd86d
@@ -2,102 +2,102 @@
> * 原文作者:[Mario Hoyos](https://medium.freecodecamp.org/@mariohoyos?source=post_header_lockup)
> * 译文出自:[掘金翻译计划](https://github.com/xitu/gold-miner)
> * 本文永久链接:[https://github.com/xitu/gold-miner/blob/master/TODO/a-beginners-guide-to-website-optimization.md](https://github.com/xitu/gold-miner/blob/master/TODO/a-beginners-guide-to-website-optimization.md)
> * 译者:
> * 校对者:
> * 译者:[Starrier](https://github.com/Starriers)
> * 校对者:[Clarence](https://github.com/ClarenceC)、[dazhi1011](https://github.com/dazhi1011)
# A beginners guide to website optimization
# 网站优化初学者指南
![](https://cdn-images-1.medium.com/max/800/1*xNt4aprSuOo2bdYg9F-6gw.jpeg)
Image courtesy of Pexels.
图片由 Pexels 提供。
I am a beginner, and I was able to achieve 99/100 in Googles optimization ranking. If I can do it, you can too.
我是一名初学者,在 Google 优化排名中,我可以达到 99/100。如果我可以做到,那么您也可以。
If youre like me, you like proof. So here are [Googles PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights/) results for [hasslefreebeats](https://www.hasslefreebeats.com), a website that I maintain and recently spent some time optimizing:
如果您和我一样,喜欢证据。下面是 [Google PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights/) 结果。[hasslefreebeats](https://www.hasslefreebeats.com) 是我维护的网站,我最近花了一些时间进行优化。
![](https://cdn-images-1.medium.com/max/800/1*HHW2mRHOGA7w_o9VxC4w7A.png)
A screenshot of my PageSpeed Insights score.
我的 PageSpeed Insights 分数截图。
I am pretty proud of these results, but I want to stress that I didnt have a clue about how to optimize a website just a couple of weeks ago. What I have to share with you today is simply the result of a whole lot of googling and troubleshooting, pains I wish to spare you.
我对这些结果感到非常自豪,但是我想强调的是,几周前我还不知道如何去优化一个网站。今天我要和大家分享的只是一大堆 Google 搜素和故障排除所得出的结果,我希望可以为您省去麻烦。
This article is broken up into subsections for each optimization, in case you want to jump around.
为了防止您想跳过,这篇文章被分成了几个小节。
I am by no means an expert, but Im confident that if you implement the techniques below, you will see results!
我绝不是专家,但我相信如果您实施以下技术,你会看到效果!
### Images
### 图片
![](https://cdn-images-1.medium.com/max/800/1*jkCxAOJPjPhKkQaen0rt4g.jpeg)
Image courtesy of Pexels (and surely optimized by Medium).
图片由 Pexels 提供 (Medium 已做优化).
As a beginner web-developer, images were not something I ever paid much mind to. I knew that adding high-quality images to my website would make it look more professional, but I never stopped to consider the effects they would have on my pages load time.
作为一个网站开发初学者,我并没有想过图片的事情。我知道向我的网站添加高质量图片会使它看上去更专业,但是我从没有停下来考虑它们对我的网页加载时间的影响。
The main thing I did to optimize my images was compress them.
我为优化图像所做的事情主要是压缩它们。
Looking back, this should have been fairly intuitive from the get-go, but it wasnt for me, so maybe it isnt for you either.
回想起来,这从一开始就非常直观,只是我没有在意,可能您也一样。
The service that I used to compress my images was [Optimizilla](http://optimizilla.com/), an easy-to-use website where you upload your images, select the level of compression you want, and then download the compressed image. I saw size decreases upwards of 70% for some of my resources, which goes a LONG way towards faster load times.
我用来压缩图片的服务是 [Optimizilla](http://optimizilla.com/), 一个易于使用的网站,那您只需上传图片,选择你要压缩的级别,然后下载压缩图片。我看到一些资源的大小减少了 70% 以上,这对于更快的加载时间有很大的帮助。
Optimizilla is hardly the only choice for your image compression needs. Some standalone, open-source software you can use is [ImageOptim](https://imageoptim.com/mac) for Mac or [FileOptimizer](https://sourceforge.net/projects/nikkhokkho/files/FileOptimizer/) for Windows. If you prefer to compress using build tools, there are [Gulp](https://www.npmjs.com/package/gulp-imagemin) and [WebPack](https://github.com/Klathmon/imagemin-webpack-plugin) plugins that should do the trick. It doesnt matter so much how you do, so long as you do. The performance gains are well worth the minimal effort.
Optimizilla 并不是您图片压缩需求的唯一选择。您可以使用一些独立的开源软件,Mac 环境下的 [ImageOptim](https://imageoptim.com/mac) 或者 Windows 环境下的 [FileOptimizer](https://sourceforge.net/projects/nikkhokkho/files/FileOptimizer/)。如果您更喜欢用构建工具进行压缩,那么可以使用 [Gulp](https://www.npmjs.com/package/gulp-imagemin) [WebPack](https://github.com/Klathmon/imagemin-webpack-plugin) 插件。无论您怎么做,只要做了,那么即使是最小的努力,也会在性能上获取提升。
Depending on your use case, it may also be worth looking at your files format. Generally speaking, jpg is going to be smaller than png. The main difference in whether I use one or the other is whether I need transparency behind the image: If I need transparency, I use png, otherwise I use jpg. You can dive deeper into the pros and cons of both [here.](https://www.digitaltrends.com/photography/jpeg-vs-png-photo-format/)
根据您的情况,可能还需要查看文件格式。一般来说,jpg 会比 png更小。我是否使用其中一个的主要区别是我是否需要图片背后的透明度:如果我需要透明度就使用 png,否则使用 jpg。您可以在 [这里](https://www.digitaltrends.com/photography/jpeg-vs-png-photo-format/)更深入地了解这两者的利弊。
Also, Google has come out with a webp format that is pretty sweet, but since its not supported on all browsers yet, Im hesitant to use it. Keep an eye out for further support in the future!
此外,Google 已经推出了一种非常贴心的 webp 格式,但由于目前没有在所有浏览器被支持,所以我还在犹豫是否使用它。会留意未来是否有进一步地更新支持!
I didnt do more than compress my images to get the results I showed you above, but if you want to optimize further [here is a great article.](https://www.frontamentals.com/practical-guide-to-images)
我没有在我的图片上做更多的压缩来获得以上展示的结果,但是如果您想进一步优化 [这里有一篇很棒的文章。](https://www.frontamentals.com/practical-guide-to-images)
### Video
### 视频
![](https://cdn-images-1.medium.com/max/800/1*9NjlazjgG3HV99ZH54_NGg.jpeg)
Photo by Terje Sollie from Pexels.
照片来自 Pexels 的 Terje Sollie。
I havent used video in any of my current projects, so I will only touch on this briefly as I do not feel I am the best resource for this, specifically.
尤其是我没有在我目前的任何项目中使用视频,所以我只会简单地涉及到这一点,因为我不觉得在这方面我这是最佳的解决方案。
This is one of those situations where I would likely let the pros do the heavy lifting. Vimeo offers an excellent platform for hosting videos where they will degrade video quality for slower connections and compress your videos to optimize performance.
在这种情况下我可能会让专业人士来做繁重的工作。Vimeo 为托管视频提供了一个很好的平台,在那里它们会降低视频质量,从而降低链接速度,并压缩您的视频以优化性能。
You could also host your videos on Youtube and then use this [youtube-dl](https://rg3.github.io/youtube-dl/) tool to download them from Youtube while configuring the videos to your websites needs.
您也可以在 YouTube 上托管视频,然后使用 [youtube-dl](https://rg3.github.io/youtube-dl/) 工具从 You Tube 下载视频,同时根据您网站的需要配置视频。
For other possible solutions, check out [Brightcove](https://www.brightcove.com/en/), [Sprout](https://sproutvideo.com/) or [Wistia](https://wistia.com/).
至于其他可能的解决方案,请查看 [Brightcove](https://www.brightcove.com/en/), [Sprout](https://sproutvideo.com/) 或者 [Wistia](https://wistia.com/).
### Gzip
### Gzip 压缩
![](https://cdn-images-1.medium.com/max/800/1*0OyByk88pz6_R9H7BGmvng.jpeg)
Get it? Zip? Image courtesy of Pexels.
了解了么? Zip 压缩? Pexels 提供的图片。
I had no idea what gzipping was when I initially deployed my website.
最初部署我的网站时,我不知道 gzip 是什么。
Long story short, gzip is a file compression format that most browsers understand and that can run behind the scenes without requiring the user to even know its happening.
长话短说,gzip 是一种大多数浏览器都能理解的文件压缩格式。它可以在幕后运行而不需要用户知道它正在发生。
Depending on where you are hosting your application, gzipping may be as simple as flipping a configuration switch to specify that you want your server to gzip files when sending them out. In my case, my website is hosted on Heroku, which does not provide this option.
根据您应用程序所在的位置,gzip 可能非常简单,只需打开配置开关,以指定您希望服务器在发送文件时对其进行 gzip 压缩。就我而言,托管我网站的 Heroku 不提供这个选项。
As it turns out, there are packages to add compression explicitly in your server code, which allows you to reap the benefits of gzipping in exchange for only a few lines of code. Using [this](https://github.com/expressjs/compression) compression middleware, [I was able to decrease the size of my Javascript and CSS bundles by 75%.](https://codeburst.io/how-i-decreased-the-size-of-my-heroku-app-by-75-1a4cf329b0ab)
事实证明,在服务器代码中有些包可以进行显式压缩。这使得您只需几行代码即可获取 gzip 的好处。使用[这个](https://github.com/expressjs/compression)压缩中间件,[我能够将 JavaScript CSS 捆绑包大小减少 75%](https://codeburst.io/how-i-decreased-the-size-of-my-heroku-app-by-75-1a4cf329b0ab)
It is worthwhile to check if your hosting service provides a gzip option. If it does not, look into how to add gzipping to your server-side code.
检查一下您的托管服务是否提供 gzip 选项是值得的。如果没有,请查看如何将 gzip 添加到服务器代码中。
### Minifying
### 最小化
![](https://cdn-images-1.medium.com/max/800/1*HoF4YTMZzbKsCi_nEbeLeQ.jpeg)
Minified pineapple courtesy of Pexels.
最小化的菠萝 Pexels 提供。
Minification is the process of removing unnecessary characters from code without affecting its functionality (whitespace, new-line characters, and so on). This allows you to decrease the size of the file you are transporting across the internet. Its also useful for obfuscating your code, which makes it harder for sneaky hackers to detect security weak-points.
最小化是在不影响代码功能(空格、换行符等)的情况下从代码中删除不必要字符的过程。这使您可以减少您正在通过互联网传输文件的大小。它也有助于混淆您的代码,这使得狡猾的黑客更难检测到安全弱点。
These days, minifying is usually done as part of the build process with Webpack or Gulp or some alternative. These build tools can have a bit of a learning curve, however, so if you are looking for easier alternatives, Google recommends [HTML-Minifier for HTML](https://github.com/kangax/html-minifier), [CSSNano for CSS](https://github.com/ben-eb/cssnano), and [UglifyJS for Javascript](https://github.com/mishoo/UglifyJS2).
如今,最小化功能通常是 Webpack Gulp 或者其他方法作为构建过程的一部分。但是这些构建工具有一些学习曲线,因此如果您正在寻找更简单的替代方法,Google 推荐 [HTML-Minifier for HTML](https://github.com/kangax/html-minifier) [CSSNano for CSS](https://github.com/ben-eb/cssnano) [UglifyJS for Javascript](https://github.com/mishoo/UglifyJS2)
### Browser-Caching
### 浏览器缓存
![](https://cdn-images-1.medium.com/max/800/1*OGT_IyEaWXw5gbFOoP_Ipg.jpeg)
Not quite how the browser stores data, but its as close as I could get. Courtesy of Pexels.
不太清楚浏览器具体如何存储数据,但它是我所能得到的最接近的。Pexels 赞助。
Storing static files in the browsers cache is a very efficient way to increase the speed of your website, especially on return visits from the same client. I was not aware, until Google told me, that some of my resources were not being cached appropriately because of missing headers on the HTTP response I was sending from my server.
将静态文件存储在浏览器的缓存中是提高网站速度的一种非常有效的方法,特别是在来自同一浏览器的回访时。直到 Google 告诉我,我的一些资源没有被适当地缓存,因为我从服务器发送的 HTTP 响应头中缺少标题,我才意识到这一点。
As soon as my home page is loaded, a request is made to my server to get data about a bunch of songs which are then rendered in a music player. I dont update the songs on this website very often, so I do not mind if a user comes to my website and sees the same songs from the last time they visited, if it will make my page load a bit faster for them.
一旦加载了我的主页,就会向我的服务器发送一个请求,以获取一堆歌曲的数据,然后在音乐播放器中解析这些歌曲。我不经常更新这个网站上的歌曲,所以如果这会是我的页面加载速度更快一些的话,我不介意用户在我的网站上看到他们上次访问的相同歌曲。
In order to get a performance boost, I added the following code to my servers response object (Express/Node server):
为了提高性能,我在服务器的响应对象 (Express/Node server) 中添加了以下代码:
```
res.append("Cache-Control", "max-age=604800000");
@@ -105,43 +105,43 @@ res.append("Cache-Control", "max-age=604800000");
res.status(200).json(response);
```
All I am doing here is appending a cache-control header to my response, which says that after one week (in milliseconds), the resources should be re-downloaded. If you update these files more often, a shorter max-age might be a good idea.
我在这里所做的就是在我的响应中附加一个说明超过一周(毫秒)应该重新下载资源的缓存控制头。如果您经常更新这些文件,缩短最长时间可能是个好主意。
### **Content Distribution Network**
### **内容分发网络**
![](https://cdn-images-1.medium.com/max/800/1*jhMPWm5Op0VRbmPC6-FX9w.jpeg)
Real-life image of a CDN, courtesy of Pexels.
现实中的 CDN 图像,Pexels 提供。
A content distribution network, or CDN, is a network that allows users from all over the world to be geographically closer to your content. If a user has to load a large image from Japan, but your server is in the United States, this will take longer than if you had a server in Tokyo.
内容分发网络(CDN)是允许来自世界各地的用户在地理上更接近您的内容的网络。如果用户必须加载来自日本的大图像,但您的服务器在美国,这将比您在东京的服务器花费更长的时间。
A CDN allows you to take advantage of a bunch of proxy servers located all over the world, allowing your content to be loaded more quickly regardless of where your end-user is located.
CDN 允许您利用分布在世界各地的一组代理服务器,无论您的最终用户位于何处,都可以更快加载您的内容。
I want to note that I was able to achieve the results you saw above **before** implementing a CDN — I simply wanted to mention them as no article about website optimization would be complete without mentioning them. Having one of these bad boys on your website is imperative if you are planning to have a worldwide audience.
我想指出的是,实现 CDN 之前,我能够实现**上面**你所看到的结果--我只是想提及它们,因为没有网站优化的文章提及到他们。如果您计划拥有全世界的读者,那么在您的网站上有一些创新是绝对必要的。
Some popular CDNs include [CloudFront](https://aws.amazon.com/cloudfront/) and [CloudFlare](https://www.cloudflare.com/lp/ddos-a/?_bt=157293179478&_bk=cloudflare&_bm=e&_bn=g&gclid=CjwKCAiA_c7UBRAjEiwApCZi8Ri3kAEt3UraYPUFUQOMTG0Xz7WGCNRUri0UNtCOUAdUMJI8osxuDRoCTx8QAvD_BwE).
一些流行的 CDNs 包括 [CloudFront](https://aws.amazon.com/cloudfront/) [CloudFlare](https://www.cloudflare.com/lp/ddos-a/?_bt=157293179478&_bk=cloudflare&_bm=e&_bn=g&gclid=CjwKCAiA_c7UBRAjEiwApCZi8Ri3kAEt3UraYPUFUQOMTG0Xz7WGCNRUri0UNtCOUAdUMJI8osxuDRoCTx8QAvD_BwE).
### Miscellaneous
### 其他方法
Heres a couple more tips to squeeze out even more juice:
这里有些能让您有所收获的内容:
* Optimize your website to load “above-the-fold” content first to increase the perceived performance of your site. One common way to do this is by [lazy-loading](https://en.wikipedia.org/wiki/Lazy_loading) images that dont show up on the landing page.
* Unless your application depends on Javascript to render HTML, such as a website built with Angular or React, then it is likely safe to load your script tags at the bottom of the body section of your HTML file. This could affect your [time-to-interactive](https://developers.google.com/web/tools/lighthouse/audits/time-to-interactive), however, so it is NOT a technique I would recommend for every situation.
* 首先通过增加您网站的感知性能优先加载“首页”来优化您的网站。一种常见的方法是[延迟加载](https://en.wikipedia.org/wiki/Lazy_loading)没有显示在登录页面上的图像。
*   除非您的应用程序依赖于 JavaScript 来渲染 HTML,例如使用 Angular 或者 React 来构建网站,那么它会在你 HTML 文件的 body 底部看似安全的区域加载你的 script 标签。即使这可能会影响您的[交互时间](https://developers.google.com/web/tools/lighthouse/audits/time-to-interactive),所以我并不会对每个情况都推荐使用这种技术。
### In Conclusion
### 总结
This is just the tip of the iceberg when it comes to optimizing your website. Depending on the amount of traffic you are receiving and the service you are providing, you could have performance bottlenecks in many different areas. Maybe you need more servers, maybe you need a server with more RAM, maybe your triple-nested for-loop could use some refactoring — who knows?
当涉及到优化您的网站时,这都只是冰山一角。根据您接受的流量和所提供的服务数量,您可能会在许多不同的领域存在性能瓶颈。也许您需要更多的服务器,也许您需要一个拥有更多 RAM 的服务器,也许您的三重嵌套 for 循环可以使用一些重构--谁知道呢?
There is no one-size-fits-all when it comes to speeding up your site, and youll ultimately have to make the best decisions for your situation based on measurements. Dont waste your time optimizing something that does not need optimizing. Analyze the performance of your site to find bottlenecks, then attack those specifically.
对于加速您的网站来说,没有一个准确无误的方法,您最终将不得不根据您的测试来做出最好的决定。不要浪费时间去优化不需要优化的东西。分析您网站的性能,找出瓶颈,然后专门解决这些瓶颈。
I hope that you found something useful in this article! As I mentioned, I still have a lot to learn in this domain. If you have any additional tips or recommendations, please leave them in the comments below!
我希望您能在这篇文章中找到一些有用的东西!正如我所提到的,我在这个领域还有很多东西要学。如果您有任何额外的提示或者建议,请将它们留在下面的评论中!
If you liked this article please give it some claps and check out:
如果您喜欢我的文章,请为我鼓掌,还有以下内容:
* [Tools I wish I had known about when I started coding](https://medium.freecodecamp.org/tools-i-wish-i-had-known-about-when-i-started-coding-57849efd9248)
* [Tools I wish I had known about when I started coding: Revisited](https://medium.freecodecamp.org/tools-i-wish-i-had-known-about-when-i-started-coding-revisited-ffb715ffd23f)
* [当我开始编码时,我希望我已经了解的工具](https://medium.freecodecamp.org/tools-i-wish-i-had-known-about-when-i-started-coding-57849efd9248)
* [当我开始编码时,我希望我已经了解的工具: 重新访问](https://medium.freecodecamp.org/tools-i-wish-i-had-known-about-when-i-started-coding-revisited-ffb715ffd23f)
Also, give me a follow on [Twitter](https://twitter.com/marioahoyos).
当然,也可以关注我的 [Twitter](https://twitter.com/marioahoyos).
---