编程知识 cdmana.com

Ultimate Guide to website front end performance optimization

image.png

The golden rule of performance :80- 90% End user response time is spent on the download front end , That is, all components on the page :img、stylesheets、scripts etc.

1. narrow HTML、CSS and JavaScript

Reducing resources means from HTML、JavaScript and CSS Delete unnecessary 、 Characters that do not need to be loaded , Such as white space characters 、 Newline characters 、 Comments and block separators .

This will speed up your load time , Because it reduces the amount of code that must be requested from the server .

Minimize plug-ins for automated task systems ——Grunt and Gulp.

narrow JavaScript Code tools ——JSMin and YUI Compressor.

2. Reduce HTTP request

When your browser gets data from the server , It USES HTTP( Hypertext transfer protocol ). It is a request between the client and the host / Respond to . Generally speaking , Web page HTTP The more requests , The slower the load . There are many ways to reduce the number of requests , Such as :
inline JavaScript—— Merge all scripts into one script , Similarly, all CSS Merge into one style sheet .( Only in very small cases )

Use CSS spirit —— Combine your background images into one image , And use CSS And attributes to display the required image fragments and reduce the assets that generate a large number of external requests, such as third-party plug-ins .

Image mapping combines multiple images into a single image . The total size is the same , But less HTTP The number of requests can increase the speed of the page .( Such as the navigation bar )

Use sessionStorage API and localStorage API Store data in the browser . Reference resources ——Web Storage api

3. Use content distribution networks (CDN)

A content delivery network is a set of networks distributed in different geographical locations web The server , They provide information to end users based on their location web Content .

When you host a web site on a single server , All user requests are sent to the same hardware . For this reason , The time required to process each request has increased . most important of all , When the user is physically away from the server , The load time will increase .

Use CDN, User requests are redirected to the nearest server . therefore , Content can be delivered to users faster , The website will run faster . This is a very expensive but very effective way to optimize loading time .

4. The time of the first byte (TTFB)

TTFB It's right web Measurement of server responsiveness . Basically , It is the time taken for the browser to receive information from the server after requesting information .

When users visit your site , Their browser sends a message to the server hosting the site HTTP request . Three steps need to be performed between the initial request and the first byte of data :DNS lookup 、 Server processing and response . A website's TTFB The calculation for the :HTTP Request time + Processing request time + HTTP response time .

image.png

By using CDN、 Fast web Host and reliable DNS provider , You can greatly reduce the overall TTFB.
Google suggestions TTFB Less than 200 millisecond .

5. Critical render path

The key rendering path is that the browser will HTML、CSS and JavaScript A sequence of steps taken to convert to pixels on the screen .

image.png

Key rendering paths include the document object model (DOM)、CSS The object model (CSSOM)、 Render tree 、 Layout and drawing .

In parsing HTML Create a document object model .HTML You can ask for JavaScript, and JavaScript It can be changed in turn DOM.HTML Include or issue style requests , Style builds... In turn CSS The object model . The browser engine combines the two to create a rendering tree . The layout determines the size and location of all content on the page . Once the layout is determined , The pixels are drawn on the screen .

Optimize critical rendering paths to improve rendering performance . Performance tips include :

  1. By delaying their download (defer attribute )、 Mark them asynchronous (async attribute ) Or eliminate them completely to minimize the number of critical resources .
  2. The number of requests required for optimization and the file size per request .
  3. By prioritizing the downloaded key resources , Optimize the loading sequence of key resources , Shorten the critical path length .

6. PRPL Pattern

PRPL It's an acronym , Describes a model for making web pages load and interact faster .

push ( Or preload ) The most important resource :

Preload It's a statement fetch request , It tells the browser to request resources as soon as possible . By means of HTML Add tags at the beginning of the document to preload key resources : rel = “Preload”

<link rel=”preload” as=”style” href=”css/style.css”>

Present the initial route as soon as possible

To improve First Paint, Lighthouse It is recommended to inline key JavaScript, And use asynchronous delay for the rest , And inline key CSS. Get rendering blocking resources by eliminating round trips with the server , This improves performance . However , From a development point of view , Inline code is harder to maintain , And cannot be cached separately by the browser .

improvement First Paint Another way to do this is to render the initial view of the page on the server side HTML. This will happen while the script is still getting 、 Display the content to the user immediately when parsing and executing . However , This may significantly increase HTML Payload of the file , This may damage Time to Interactive, Or the time it takes for your application to become interactive and responsive to user input .

Pre cache remaining resources

By acting as an agent ,service worker You can get resources directly from the cache instead of the server during repeated access . This not only allows users to use your application while offline , Moreover, the page loading time will be shorter when repeated visits .

Use third-party libraries to simplify generation service worker The process of , Unless you have more complex caching requirements than the library can provide . for example ,Workbox Provides a set of tools , Allows you to create and maintain service worker To cache resources .

Delay loading other routing and non critical resources

To send a smaller JavaScript Payload ( Contains only the code that the user needs to initially load the application ), The whole... Can be split as needed bundle And inert loading blocks .

Once you've successfully split your bag , Preload the more important part . Preloading ensures that browsers get and download more important resources faster .

7. Reduce the use of network Fonts

Web fonts have become very popular in website design . Unfortunately , The use of Web fonts has a negative impact on page rendering speed . Google fonts, etc Web Fonts add extra... To external resources HTTP request .Web Fonts also appear blocked . The following measures will help you reduce the size of Web font traffic :

  • Use modern formats in modern browsers WOFF2
  • Contains only the character set used on the website
  • Just choose the style you want
  • Host fonts are local or prefetched
  • Use Base64 The code is stored in LocalStorage in

image.png

8. Enable browser caching

For resources that rarely change , Using browser caching is crucial . under these circumstances , The recommended maximum age is 7 God . There are different types of HTTP head , Such as :Cache-Control, Pragma and Expires.

The most important HTTP One of the cache headers may be a header composed of a set of instructions , Allows you to define when to respond 、 How and for how long . When browsers store copies of resources for faster access , It will happen HTTP cache . The client is in HTTP The standard instructions that can be used in the request are as follows .

Cache-Control: max-age=
Cache-Control: max-stale[=]
Cache-Control: min-fresh=
Cache-Control: no-cache
Cache-Control: no-store
Cache-Control: no-transform
Cache-Control: only-if-cached

image.png

**no-cache:** The response can be stored in any cache , Even if the response is usually not cacheable . however , The stored response must be verified by the source server before use .

**no-store:** The response may not be stored in any cache . Be careful , This does not prevent a valid pre-existing cached response from being returned . The client can also be set to clear the existing cached response , Because this will force the cache to use server.max-age=0 Revalidation .

**max-age=:** Maximum resource lifetime . The difference is , This instruction is relative to the requested time .

**must-revalidate:** Indicates that once a resource becomes obsolete , Without successful authentication on the original server , Cache cannot use stale copies .

**public:** The response can be stored in any cache , Even if the response is usually not cacheable .

**Expires——** This header specifies the expiration date of the cache resource / Time . for example , Indicates that the cache resource is in 2017 year 5 month 13 In the morning of GMT on the th 7 Point expiration . When included max-age The directive cache-control When the header appears ,expires The header is ignored .

**ETag——** Respond to the headlines , According to a token ( String in quotation marks , for example ,) Identify the version of the service content , The token will change after the resource is modified . If a token does not change before the request is made , The browser will continue to use its local version .

**Vary——** Determine the response that must match the cache resource to be considered a valid header . for example , The header file specifies that a cached version must exist for each user agent and language combination .Vary: Accept-Language, User-Agent

9. Enable Gzip Compress

Gzip It's a compressed form , It's putting web pages 、CSS and JavaScript Before sending to the browser , Compress them at the server layer .

On user side , The browser decompresses the file and displays the contents . This method can be used for all files on the website . Such website performance optimization is easy to achieve , It can make a big difference .

According to Yahoo , This can reduce about 70% Download time . Because now 90% All Internet traffic is supported by Gzip Browser transfer , So it is a good choice to improve the speed of the website .

image.png

10. Reduce redirection

When you move and delete pages , Redirection is usually necessary , And it's the best way to eliminate the problem of broken links .

But if there are too many HTTP request , There will be additional HTTP request , This will have a negative impact on speed , Especially on mobile devices .

This means it's best to keep them to a minimum . in fact , Google says , Ideally , Website owners should eliminate them completely .

You can start using screaming frogs to quickly identify all the redirects currently on your website . Then you have to check whether they have the necessary purpose , Leave only the key .

11. Move your website to a better host

There are three possible types of hosting :

Shared host

The most popular type of hosting used worldwide is shared hosting . This is the cheapest way to get your website online at a low cost in a short time . Choosing a fast network host to ensure better optimization is crucial .

Managed by sharing , You can share with other sites that also use this server CPU、 Disk space and RAM. This is shared hosting VPS Or the main reason why the dedicated server is fast .

Virtual private server (VPS) trusteeship

VPS It's much faster . It uses multiple servers for content distribution . Use VPS, You can share the server with other users , And have their own virtual server part , Your configuration will not affect other clients .
If your website has average traffic , Or your e-commerce website has experienced a surge in traffic in some periods ,VPS Will be your best solution .

Dedicated server

The most expensive hosting option is to use a dedicated server , It can be your own physical server . under these circumstances , You need to pay the server rent and hire a system administrator to maintain it .
Another way is from AWS、Microsoft Azure、Google Or other public cloud providers rent private cloud resources . These two methods can also be combined into hybrid clouds . Use a dedicated server , All resources belong to you only , You have complete control over them . Cloud infrastructure can also add unlimited and on-demand scalability under multiple packages .
Serverless architecture Is another option to completely remove the maintenance and server setup process .

image.png

12. Optimize the size of pictures on the website

Everyone likes eye-catching pictures . In successful e-commerce websites , Images are a vital part . Add a lot of photos to your product page 、 Images and graphics can improve user stickiness . The negative impact of using pictures is , They are usually large files , Will slow down the website .

The best way to reduce the image size without affecting the image quality is to use ImageOptim、JPEGmini or Kraken And other tools to compress the image . This process may take some time , But it's worth it .

Another way to reduce the image size is to use HTML Response images and properties , Resize the image according to the user's display properties .

13. Use Debouncing and Throttling

Debouncing and Throttling Are two widely used technologies , It can improve the performance of code executed repeatedly over a period of time .

Conclusion

We've covered most of the technologies to speed up and optimize website performance . I hope you find this useful .

At the end of the article eggs

Recently, I cooperated with silent Wang Er to carry out an open source project : In order to learn for Xiaobai Java Offer some help , We created LearnJava Online learning sites . meanwhile , We have also opened the source code of the website —— The name is programming portal , In order to let everyone learn Java When , One more hand training program .

Address :https://github.com/itwanger/JavaLearnSource
Welcome to star! Love you !

版权声明
本文为[Programmer Shi Lei]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/08/20210809185008869Z.html

Scroll to Top