如何提高页面性能并充分利用主机

tech2023-02-27  101

This article was sponsored by Hosting Facts. Thank you for supporting the sponsors who make SitePoint possible.

本文由Hosting Facts赞助。 感谢您支持使SitePoint成为可能的赞助商。

You can spend months building an amazing website only to let yourself down at the last stage with inadequate optimization or hosting.

您可能需要花费数月的时间来建立一个出色的网站,但最后却因优化或托管不足而陷入困境。

Average page weight has reached 2,300KB and increases around 15% every year. The rise of projects such as Google Accelerated Mobile Pages, Facebook Instant Articles and ad-blockers highlight user frustration with the web we’ve created. Obese pages:

平均页面重量已达到2300KB,并且每年以15%的速度增长 。 诸如Google Accelerated Mobile Pages , Facebook Instant Articles和广告拦截器之类的项目的兴起凸显了用户对我们创建的网络的不满。 肥胖页面:

are slower to load and render

加载和渲染较慢 struggle on mobile networks and may cost users money

在移动网络上苦苦挣扎,可能会花费用户金钱 are less responsive on slower devices and smartphones

在较慢的设备和智能手机上React较慢 will affect your search engine rankings

会影响您的搜索引擎排名 are more difficult to update and maintain.

更难以更新和维护。

Few developers bother to optimize their sites so why should you?

很少有开发者会去优化他们的网站,那为什么要呢?

The reason: there’s no downside. Your search engine rankings improve. Your users benefit from a slicker experience. Your conversions increase. Your hosting charges drop. Unlike real life, the most drastic weight loss can be achieved with minimal effort…

原因: 没有缺点 。 您的搜索引擎排名会提高。 您的用户将受益于流畅的体验。 您的转化次数增加。 您的托管费用下降。 与现实生活不同,只需花费很少的精力即可实现最大幅度的减肥……

网站分析工具 (Site Analysis Tools)

Assess the scale of any problems before making changes. Several free tools are available which report the number of requests, file sizes and server response speed. Some provide improvement suggestions.

进行更改之前,请评估任何问题的严重性。 有几种免费工具可用于报告请求数量,文件大小和服务器响应速度。 有些提供了改进建议。

Pingdom Website Speed Test

Pingdom网站速度测试

Google PageSpeed Insights

Google PageSpeed见解

GTmetrix

GTmetrix

WebPageTest

WebPageTest

Web Page Analyzer

网页分析器

Alternatively, use the Network or Profiling tools in your browser’s development tools to assess your site. Make a copy of the statistics so you can compare improvements later.

或者,使用浏览器开发工具中的“ 网络”或“ 分析”工具来评估您的站点。 复制统计信息,以便以后可以比较改进。

The following sections provide optimization suggestions starting with the easiest changes.

以下各节提供从最简单的更改开始的优化建议。

查找合适的网络主机 (Find a Suitable Web Host)

Your site may have taken considerable time and money to create. Should you really host it on a $5 per month service?

您的网站可能要花费大量的时间和金钱来创建。 您是否应该将其托管在每月5美元的服务上?

Take time to assess whether you need space on a shared server, your own private server or a cloud-based virtual server. Read hosting reviews at sites such as Hosting Facts and seek advice from others with similar requirements. At this moment, they’re suggesting to use A2 Hosting or A Small Orange.

花时间评估您是否需要共享服务器,自己的私有服务器或基于云的虚拟服务器上的空间。 在“ 托管事实”等网站上阅读托管评论,并从有类似要求的其他网站寻求建议。 目前,他们建议使用A2 Hosting或A Small Orange 。

使用内容传送网络(CDN) (Use a Content Delivery Network (CDN))

Browsers limit HTTP requests to between four and eight simultaneous connections per domain. Loading 40 page assets at once is not possible – files are queued on each request thread.

浏览器将HTTP请求限制为每个域同时进行四个到八个连接。 无法一次加载40页资产–文件在每个请求线程上排队。

In addition, your users may be located in a different geographical location to your server. A user in France would see a faster response from a UK-based server than similar hardware in Australia.

此外,您的用户可能位于与服务器不同的地理位置。 与澳大利亚的类似硬件相比,法国的用户会看到来自英国服务器的响应速度更快。

A CDN increases download speeds by distributing web site assets to other servers. Those machines can be physically closer to the user and run from different domains which more than doubles HTTP request limits.

CDN通过将网站资产分配到其他服务器来提高下载速度。 这些机器在物理上可以更接近用户,并且可以在不同的域中运行,这使HTTP请求限制增加了一倍以上。

CDNs have become simpler to use and many automatically handle assets once you’ve configured DNS settings. Popular options include:

配置了DNS设置后,CDN变得更易于使用,并且许多CDN会自动处理资产。 热门选项包括:

CloudFlare

CloudFlare

MaxCDN

最大CDN

Amazon CloudFront

亚马逊CloudFront

启用GZIP压缩 (Enable GZIP Compression)

Around a third of websites do not enable Gzip compression yet it can drastically reduce the amount of data sent to the browser. Gzip compression is often set by your web host on the server – contact them for further advice.

约有三分之一的网站未启用Gzip压缩,但可以大大减少发送到浏览器的数据量。 Gzip压缩通常是由服务器上的Web主机设置的–请与他们联系以获取进一步的建议。

启用缓存 (Enable Caching)

Caching ensures a browser downloads asset files once. The local version is retained until your website instructs it to fetch an update. The first page load won’t be faster but subsequent page loads will be considerably improved.

缓存可确保浏览器一次下载资产文件。 本地版本将保留,直到您的网站指示它获取更新为止。 最初的页面加载不会更快,但随后的页面加载将会得到显着改善。

There are plugins for Content Management Systems such as WordPress which make caching simple, e.g. W3 Total Cache or WP Super Cache.

有诸如WordPress之类的内容管理系统的插件,可以简化缓存,例如W3 Total Cache或WP Super Cache 。

Other systems can adopt technologies such as Expires, Last-Modified, Keep-Alive or Etag in the HTTP header. Your host may provide configuration options or you can define your own. For example, an Apache .htaccess setting to cache all images for one month:

其他系统可以在HTTP标头中采用Expires , Last-Modified , Keep-Alive或Etag等技术 。 您的主机可以提供配置选项,也可以定义自己的选项。 例如,Apache .htaccess设置将所有图像缓存一个月:

<IfModule mod_expires.c> ExpiresActive On <FilesMatch "\.(jpg|jpeg|png|gif|svg)$"> ExpiresDefault "access plus 1 month" </FilesMatch> </IfModule>

优化您的媒体 (Optimize Your Media)

Images account for more than 60% of page weight. The average page requests 55 separate images at 1,457KB, 126KB of fonts, 400KB of video and 45KB of Flash. This seems slightly preposterous given the current trend for simplistic, plain-colored flat-designs!

图片占页面重量的60%以上 。 平均页面需要55张单独的图像,分别为1,457KB,126KB字体,400KB视频和45KB Flash。 鉴于当前简单化,纯色平面设计的趋势,这似乎有些荒谬!

The first step: remove unnecessary assets. Do you need that background video, hero image, italic font or 300 icons few will ever see? Can you use a subset of a font? Could you replace some images with CSS3 effects such as gradients or borders?

第一步: 清除不必要的资产 。 您是否需要背景视频,英雄图像,斜体字体或300个很少见到的图标? 可以使用字体的子集吗? 您能否用CSS3效果(例如渐变或边框)替换某些图像?

Presuming an image is required, ensure you use the most efficient format. In general:

假定需要图像,请确保使用最有效的格式。 一般来说:

SVG is suitable for line diagrams

SVG适用于线图 Web fonts may be an option for single-color icons

Web字体可能是单色图标的选项 PNG or perhaps GIF is best for smaller images with clear color definitions such as icons, buttons and screenshots

PNG或GIF最适合具有清晰颜色定义的较小图像,例如图标,按钮和屏幕截图 JPG is best for photographs or anything where fine detail is less important.

JPG最适合照片或其他细节不重要的应用。

If in doubt, experiment with different types until you find the best compromise between quality and file size.

如有疑问,请尝试不同的类型,直到找到质量和文件大小之间的最佳平衡。

Large images should be resized to reduce the resolution. An entry-level smartphone camera produces high-resolution photographs of several megabytes but you rarely need an image greater than 2,000 pixels wide for the best of today’s screens.

大图像应调整大小以降低分辨率。 入门级智能手机相机可拍摄几兆字节的高分辨率照片,但您几乎不需要宽于2,000像素的图像就能获得当今最好的屏幕。

Next: ensure your images are the optimal size. Few graphics packages remove all possible data and most will retain unnecessary colors or EXIF meta data such as dates, locations and camera settings. One-off compression tasks can be achieved using online tools such as TinyPNG/JPE or smush.it. Installable processing tools such as OptiPNG, PNGOUT, jpegtran and jpegoptim can bulk-compress images. You can introduce compression systems such as imagemin into your build process or CMS users have options such as WP Smush which automatically compress uploaded files.

接下来:确保您的图像是最佳尺寸。 很少有图形包删除所有可能的数据,并且大多数将保留不必要的颜色或EXIF元数据,例如日期,位置和相机设置。 一次性压缩任务可以使用TinyPNG / JPE或smush.it等在线工具来完成。 OptiPNG , PNGOUT , jpegtran和jpegoptim等可安装的处理工具可以批量压缩图像。 您可以在构建过程中引入诸如imagemin之类的压缩系统,或者CMS用户可以使用诸如WP Smush之类的选项来自动压缩上传的文件。

Smaller images can be combined into a single image sprite to reduce the number of HTTP requests. This has less of an advantage in HTTP/2 but icons used on every page can still benefit from being combined.

较小的图像可以合并为一个图像精灵,以减少HTTP请求的数量。 这在HTTP / 2中的优势较小,但是每个页面上使用的图标仍然可以从组合中受益。

Finally, consider Base64-encoded inline data URIs for smaller, regularly-used images, e.g.

最后,考虑使用较小的,经常使用的图像进行Base64编码的内联数据URI,例如

.bullet { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC"); }

This reduces the number of requests although maintenance can be more difficult. Online tools such as DataURL.net and data:URI Generator are fine for one-off conversions. There may also be encoder plugins for your editor/IDE but the easiest solution is PostCSS Assets – a PostCSS plugin – which magically converts any image, e.g.

尽管维护可能会更加困难,但是这减少了请求的数量。 在线工具(如DataURL.net和data:URI Generator)适合一次性转换。 您的编辑器/ IDE也可能有编码器插件,但是最简单的解决方案是PostCSS Assets ( PostCSS插件) ,该插件神奇地转换了任何图像,例如

.inline { background-image: inline('image.png'); }

连接并缩小CSS和JavaScript (Concatenate and Minify CSS and JavaScript)

The average page loads 360KB of JavaScript distributed over 22 separate files and 76KB of CSS in 8 stylesheets. Some of these may be provided by third-party social media or advertising widgets but your own files can be:

平均页面加载8个样式表中分布在22个单独文件中的360KB JavaScript和76KB CSS。 其中一些可能由第三方社交媒体或广告窗口小部件提供,但您自己的文件可以是:

Concatenated to join all code into a single file to reduce HTTP requests, and

串联以将所有代码合并到一个文件中以减少HTTP请求,并且

Minified to remove unnecessary comments and whitespace. More extreme tools can rename variables and functions to shorter alternatives, e.g. launchWidget() becomes w().

缩小以删除不必要的注释和空格。 更多极端的工具可以将变量和函数重命名为更短的替代方法,例如launchWidget()变为w() 。

For a simpler graphical interface, a tool such as Koala provides CSS and JavaScript compression options.

对于更简单的图形界面,诸如Koala之类的工具提供了CSS和JavaScript压缩选项。

Pre-processors such as Sass, LESS and Stylus or build tools including cssnano for PostCSS can optimize CSS whenever you make a change.

每当您进行更改时,诸如Sass , LESS和Stylus之类的预处理器或包括用于PostCSS的cssnano在内的构建工具都可以优化CSS。

JavaScript can be a little more difficult since source order will be critical. You could consider a system such as Browserify to bundle dependencies. I often use a simpler Gulp plugins including:

JavaScript可能会更困难一点,因为源顺序至关重要。 您可以考虑使用诸如Browserify之类的系统来捆绑依赖项。 我经常使用更简单的Gulp插件,包括:

gulp-deporder to control dependencies. An optional comment at the top of each source file determines a suitable order, e.g. // requires: config.js, lib.js

gulp-deporder控制依赖关系。 每个源文件顶部的可选注释确定合适的顺序,例如//要求:config.js,lib.js

gulp-concat to concatenate to a single file

gulp-concat连接到单个文件

gulp-strip-debug to remove console and debugger statements

gulp-strip-debug删除控制台和调试器语句

gulp-uglify to minify.

gulp-uglify缩小。

HTTP/2 may make some of these techniques redundant if you use different CSS and JavaScript assets on each page but it should still be considered for files which change less frequently.

如果在每个页面上使用不同CSS和JavaScript资产,HTTP / 2可能会使其中某些技术变得多余,但是对于更改频率较低的文件,仍应考虑使用HTTP / 2。

删除不必要的代码 (Remove Unnecessary Code)

It is easier to add bulk than remove it but I suspect you could remove half the code from most sites without making a noticeable difference. The main culprits:

添加批量比删除批量代码更容易,但是我怀疑您可以从大多数站点删除一半的代码而不会产生明显的变化。 罪魁祸首:

CMS主题和模板 (CMS Themes and Templates)

Most themes are generic to appeal to a wide range of users. You may only use a fraction of the features so check whether a more lightweight alternative is available.

大多数主题都是通用的,以吸引广泛的用户。 您可能只使用了部分功能,因此请检查是否有更轻巧的替代品。

CMS插件 (CMS Plugins)

Avoid using plugins unless it’s absolutely necessary. In general, front-end plugins such as carousels or widgets are the worst offenders since they often contain separate sets of CSS and JavaScript.

除非绝对必要,否则避免使用插件。 通常,诸如轮播或窗口小部件之类的前端插件是最糟糕的违规者,因为它们通常包含单独CSS和JavaScript集。

CSS框架 (CSS Frameworks)

Frameworks such as Bootstrap contains a range of styles – most of which you’ll never use. Tools such as UnCSS can analyze your pages and identify unnecessary rules.

诸如Bootstrap之类的框架包含多种样式-您绝不会使用其中的大多数样式。 UnCSS之类的工具可以分析您的页面并识别不必要的规则。

JavaScript框架 (JavaScript Frameworks)

Avoid using more than one framework and consider smaller or modular options where possible. You may be able to dump your framework altogether.

避免使用多个框架,并尽可能考虑使用较小或模块化的选项。 您可能可以完全转储框架 。

JavaScript特效 (JavaScript Effects)

Simple effects such as sliding and fading out can be implemented using lightweight CSS3 animations and transformations rather than less efficient JavaScript.

可以使用轻量级CSS3动画和转换而不是效率较低JavaScript来实现简单的效果(如滑动和淡出)。

社交媒体小部件 (Social Media Widgets)

That innocuous like button can carry half a megabyte of hidden code. They are rarely necessary – link is all you require.

那种无害的按钮可以承载半兆字节的隐藏代码 。 它们很少是必需的- 链接就是您所需要的 。

广告 (Advertising)

If you sign up to 57 advertising networks, each will provide their own chunk of code which slows your site. Assess your revenues and drop less profitable widgets.

如果您最多注册57个广告网络,则每个网络都会提供自己的代码块,这会降低您的网站速度。 评估您的收入并丢弃利润较低的小部件。

进一步优化 (Further Optimizations)

The options above will make a noticeable difference to your website speed without time-consuming changes. Re-run your pages through the tools above to verify the savings and check whether usage and conversions have increased.

上面的选项将对您的网站速度产生明显的影响,而无需进行耗时的更改。 通过上面的工具重新运行您的页面,以确认节省的费用并检查使用率和转化次数是否有所增加。

For more radical optimizations…

有关更彻底的优化…

采用构建流程 (Adopt a Build Process)

The most conscientious developer will forget to compress an image or concatenate CSS when it’s a manual task. A build process can automate tedious tasks on the fly; it’s easy to minify JavaScript when it’s done for you whenever you make a change.

最认真的开发人员在执行手动任务时会忘记压缩图像或将CSS连接起来。 构建过程可以使繁琐的任务自动化。 只要您进行更改,就可以轻松缩小JavaScript。

The two most popular options are Gulp and Grunt but there are solutions for most languages and systems. The initial set-up will take a little time but your improved workflow will save hours of effort later.

最受欢迎的两个选项是Gulp和Grunt,但是大多数语言和系统都有解决方案。 初始设置将花费一些时间,但是改进的工作流程将节省以后的工作时间。

简化您的设计 (Simplify Your Design)

Many modern websites and applications eschew complexity to provide a streamlined, customer-focused experience. Simplification can be difficult and it’s often easier to start the project again. Question all feature requests or demand that a feature is removed for every one you add.

许多现代网站和应用程序都避开了复杂性,以提供简化的,以客户为中心的体验。 简化可能很困难,并且重新启动项目通常更容易。 对所有功能请求提出疑问,或者要求您为添加的每一项功能都将其删除。

考虑一个静态站点 (Consider a Static Site)

A CMS is overkill for the majority of websites. Few receive more than a couple of updates a week yet a CMS remains running in the background churning out page content which rarely changes. An alternative is a static site generator. These offer many CMS benefits such as templates but generate a series of flat HTML files with better performance, security and reliability.

对于大多数网站来说,CMS都是过大的。 很少有人每周收到两次以上的更新,但是CMS仍在后台运行,搅动很少更改的页面内容。 一种替代方法是静态站点生成器 。 它们提供了许多CMS好处,例如模板,但生成了一系列具有更好性能,安全性和可靠性的平面HTML文件。

改变您的发展生活方式 (Change Your Development Lifestyle)

There’s little excuse for 2.3MB pages when content rarely exceeds several hundred words. It’s easy to neglect performance when you’re rapidly developing a site for minimal cost. But what is the point when the result is a slow, clunky product no one wants to use?

当内容很少超过数百个单词时,2.3MB页面几乎没有任何借口。 当您以最小的成本快速开发站点时,很容易忽略性能。 但是,当结果是没人要使用的缓慢,笨重的产品时,那又有什么意义呢?

Plan performance from the start. Your clients may not appreciate the benefits immediately but the long-term rewards of higher rankings and improved engagement will help your project stand out. Consider:

从一开始就计划性能。 您的客户可能不会立即欣赏到这些好处,但是更高的排名和更好的参与度带来的长期回报将帮助您的项目脱颖而出。 考虑:

limiting your connectivity. Access your site in an area with poor mobile coverage or on a crowded public network. Your frustration could be experienced by thousands of users every day.

限制您的连接。 在移动覆盖率差的区域或拥挤的公共网络上访问您的站点。 每天成千上万的用户可能会遇到您的挫败感。 assessing weight in every project and question every asset added to the page.

评估每个项目的权重,并对添加到页面的每个资产提出疑问。

Web page obesity is an epidemic but it’s evident few developers care. Create slimline pages to learn valuable skills which help you retain and gain new clients. Further reading:

网页肥胖是一种流行病,但显然很少有开发人员关心。 创建细线页面以学习宝贵的技能,这些技能可以帮助您留住并赢得新客户。 进一步阅读:

How to Speed up Your Website

如何加快您的网站

The Complete Guide to Reducing Page Weight

减少页面重量的完整指南

翻译自: https://www.sitepoint.com/how-to-improve-page-performance-and-make-the-most-of-your-hosting/

最新回复(0)