Front-end optimization solution-CDN optimization

The front-end CDN optimization scheme mainly includes:

1: The domain name for loading resources uses CDN: Static resources referenced in the front-end page, such as css, js, pictures, etc., can be accelerated by CDN. Upload the resource to the CDN, and then refer to the resource link on the CDN in the page.

http://www.example.com/images/logo.png
 

The address after using CDN is:

http://cdn.example.com/images/logo.png
 

Two: Use CDN to speed up font loading: If font files are used in the page, you can consider using CDN to speed up the loading of font files.

By using a CDN, fonts can be loaded on the server closest to the user, resulting in faster font loading.

Here are the steps to use CDN to speed up font loading:

1. Find a reliable font CDN service provider. Google Fonts, Adobe Fonts, and Fonts.com all offer CDN services. You may also use other third-party service providers.

2. Embed the font CDN link in your HTML file. The link format is similar to the following example:

<link href='https://fonts.googleapis.com/css?family=Open + Sans' rel='stylesheet'>
 

3. Apply the font name in your CSS stylesheet. For example:

body {
    font-family: 'Open Sans', sans-serif;
}
 

4. Make sure the scenario was successful by using browser developer tools to check that the font is loaded from the CDN.

Three: Set cache control: Set cache control for static resources, which can effectively reduce the number of HTTP requests for pages and improve page loading speed. Set Expires and Cache-Control response headers to control browser caching.

Expires and Cache-Control are HTTP response header fields used to control browser caching behavior.

Expires specifies the expiration time of the response, telling the browser that resources can be obtained directly from the browser cache before the expiration time. The expiration time is the server time, and a fixed time needs to be set, for example, the specified resource expires after 5 minutes:

Expires: Wed, 21 Oct 2019 07:28:00 GMT

Cache-Control means cache control, which can specify the behavior of the cache, such as whether to cache, cache time, etc. Commonly used commands are:

  • public: Indicates that the response can be cached by all users, including CDN, etc.
  • private: Indicates that the response can only be cached by a single user, and cannot be cached by CDN, etc.
  • no-cache: Indicates that the browser needs to re-verify the validity of the cache.
  • max-age: Specifies the maximum time that a resource can be cached, for example, the specified resource can be cached for 10 minutes:
Cache-Control: max-age=600

When setting Expires and Cache-Control, you can set two response headers at the same time, such as:

Expires: Wed, 21 Oct 2019 07:28:00 GMT
Cache-Control: max-age=600, public

This means that the resource can be cached by all users before the expiration time, and can be cached for 10 minutes.

Four: Disable unnecessary cookies: For static resource requests, there is no need to set cookies, so unnecessary cookies can be disabled.

Disabling unnecessary cookies can reduce the size of HTTP request headers, thereby improving response speed. This can be done on the server side by setting the HttpOnly attribute or using a browser plug-in.

The HttpOnly attribute is added when setting the cookie, through which the cookie can be prohibited from being accessed by client-side JavaScript. In this way, cookies cannot be used for cross-site scripting attacks, and the size of cookies can also be reduced. The following response headers can be set on the server side:

Set-Cookie: mycookie=xxx; HttpOnly

Cookies can be selectively disabled through the use of browser plug-ins. For example, the EditThisCookie plug-in of Chrome browser can manage cookies conveniently, and can disable or delete unnecessary cookies.

Five: Asynchronous loading of js: For some js that does not need to be loaded immediately, you can use asynchronous loading to avoid affecting the page loading speed.

Asynchronous loading (Asynchronous Loading) is a common method to optimize web page performance, which can make pages load faster and improve user experience. Loading js files asynchronously can avoid blocking page rendering and speed up page loading. Here are two ways to implement asynchronous loading of js:

1. Use the async attribute

In HTML5, adding the async attribute can load js files asynchronously, for example:

<script src="your-script.js" async></script>

In this way, the browser will download and execute your-script.js file asynchronously without blocking the rendering of the page. It should be noted that loading js files asynchronously may change the execution order of the files, and it is necessary to ensure the dependencies between different files.

2. Use dynamic creation of script tags

Another way to achieve asynchronous loading of js is to use JavaScript to dynamically create script tags, for example:

var script = document.createElement('script');
script.src = 'your-script.js';
document.head.appendChild(script);

This way, the browser also downloads and executes your-script.js file asynchronously, making the page load faster. Compared with using the async attribute, using dynamically created script tags can better control the dependencies between files, and can load different js files asynchronously while ensuring the order of execution.

Six: Use the HTTP2 protocol: The HTTP2 protocol can load resources and files faster, thereby improving the response speed of the website. Most CDN service providers support the HTTP2 protocol.

Using the HTTP2 protocol is an effective way to optimize website performance, which can speed up web page loading and improve user experience. Compared with the HTTP1.1 protocol, the HTTP2 protocol has the following advantages:

  1. Multiplexing: The HTTP2 protocol supports multiplexing, which can transmit multiple requests and responses simultaneously in one connection, thereby avoiding the head-of-line blocking problem in HTTP1.1.

  2. Binary transmission: The HTTP2 protocol uses binary format to transmit data, which replaces the text format in HTTP1.1, reduces the size of the transmitted data, and thus improves the transmission efficiency.

  3. Header compression: The HTTP2 protocol uses the HPACK algorithm to compress request and response headers, reducing the size of transmitted data and improving transmission efficiency.

  4. Server push: The HTTP2 protocol supports server push, which can actively push some resources to the client before the client sends a request to speed up page loading.

To use the HTTP2 protocol, the following conditions need to be met:
  1. The website must use the HTTPS protocol, because the HTTP2 protocol can only be used on the HTTPS protocol.

  2. The server and client must support the HTTP2 protocol. Most modern browsers and web servers already support the HTTP2 protocol, but you need to check whether additional configuration is required.

  3. Make sure that the resource size of the website is suitable for the multiplexing and header compression of the HTTP2 protocol. Multiplexing and header compression may introduce additional overhead if the resources are too small.

Seven: DNS prefetching: DNS prefetching can be used to obtain the DNS resolution results of third-party domain names in advance, thereby increasing the resource request speed.

DNS prefetching is a technique to optimize website performance, which can reduce DNS query time and speed up webpage loading speed. DNS query is the first step when a browser loads a web page. It needs to request the DNS server to resolve the IP address corresponding to the domain name of the website. DNS prefetching can resolve the IP address corresponding to the domain name to be used in the webpage in advance before the browser starts to load the webpage, thereby speeding up the DNS query process.

To use DNS prefetching, you can add the following code to the HTML code in the head of the web page:

<link rel="dns-prefetch" href="//example.com">

Among them, the href attribute specifies the domain name to be prefetched. Multiple prefetch domain names can be added on the same page, one row for each domain name.

Although DNS prefetching can speed up page load times, overuse of DNS prefetching can also cause some problems. If many domain names are prefetched, it will increase network load and bandwidth overhead, and may cause DNS cache pollution. Therefore, the number of domain names to be prefetched should be selected according to the actual situation of the website.

Eight: Gzip compression: Using Gzip compression can reduce the size of resource requests, reduce response time, and improve performance.

Gzip compression is a commonly used web page performance optimization technology, which can reduce the size of text files such as HTML, CSS, JavaScript, etc., thereby accelerating page loading speed and reducing network transmission overhead. Gzip compression takes advantage of the repetition of text files, keeps only one copy of the repeated content, and replaces multiple repeated content with a reference to these repeated content, and only one copy of the content is transmitted during transmission, thereby reducing the network Transmission overhead.

Generally speaking, you can enable the Gzip compression function on the server side. When the server sends a file, it will judge whether the client supports Gzip compression. If it supports it, it will compress the file and send it to the client. Most modern browsers support Gzip compression, so you can enable Gzip compression on the server side to improve website performance.

For Apache servers, Gzip compression can be enabled by adding the following code in the .htaccess file:

<IfModule mod_deflate.c>
    # force deflate for mangled headers
    #developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*) + |[X~ -]{4,13}$ HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>

    # HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
    <IfModule filter_module>
        Filter Declare COMPRESS
        FilterProvider COMPRESS DEFLATE resp=Content-Type $text/html
        FilterProvider COMPRESS DEFLATE resp=Content-Type $text/css
        FilterProvider COMPRESS DEFLATE resp=Content-Type $text/plain
        FilterProvider COMPRESS DEFLATE resp=Content-Type $text/xml
        FilterProvider COMPRESS DEFLATE resp=Content-Type $text/x-component
        FilterProvider COMPRESS DEFLATE resp=Content-Type $application/javascript
        FilterProvider COMPRESS DEFLATE resp=Content-Type $application/json
        FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xml
        FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xhtml + xml
        FilterProvider COMPRESS DEFLATE resp=Content-Type $application/rss + xml
        FilterProvider COMPRESS DEFLATE resp=Content-Type $application/atom + xml
        FilterProvider COMPRESS DEFLATE resp=Content-Type $application/vnd.ms-fontobject
        FilterProvider COMPRESS DEFLATE resp=Content-Type $image/svg + xml
        FilterProvider COMPRESS DEFLATE resp=Content-Type $application/x-font-ttf
        FilterProvider COMPRESS DEFLATE resp=Content-Type $font/opentype
        Filter Chain COMPRESS
        FilterProtocol COMPRESS DEFLATE change=yes;byteranges=no
    </IfModule>

    <IfModule!mod_filter.c>
        # Legacy versions of Apache
        AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
        AddOutputFilterByType DEFLATE application/javascript
        AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
        AddOutputFilterByType DEFLATE application/xhtml + xml application/rss + xml application/atom + xml
        AddOutputFilterByType DEFLATE image/svg + xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
    </IfModule>
</IfModule>

The above is the configuration method for the Apache server. In other servers, the specific configuration method may be different. You can check the corresponding server documentation for more information.

Nine: Image optimization: Large images can be cropped and compressed to reduce file size and improve page loading speed.

The commonly used front-end image optimization techniques are as follows:

  1. Compress pictures: Use professional picture compression tools, such as TinyPNG, JPEGmini, etc., to compress the size of the picture to a smaller size, thereby reducing the file size. For images in PNG format, lossy compression can be used to reduce the file size.

  2. Use WebP format pictures: The WebP format pictures developed by Google can compress the picture size more efficiently, thereby reducing the file size and improving the loading speed of the website. However, WebP format images are not yet supported on some older browsers.

  3. Image lazy loading: For some large images, you can use image lazy loading to optimize the loading speed. That is, the pictures on the page are loaded in segments. When the user scrolls the page to a certain position, the pictures below the position are loaded, thereby reducing the loading time of the first screen.

  4. Use appropriate image formats: For different types of images, choosing appropriate image formats can reduce file size. For example, for icons, simple vector graphics, etc., you can choose to use pictures in SVG format; for complex images such as photos, you can choose to use pictures in JPEG format.

  5. CDN Acceleration: Using the CDN acceleration service can cache pictures on the CDN server, thereby speeding up the loading speed of pictures, reducing the number of requests to the original server, and improving website performance and user experience.

Through the application of the above picture optimization technology, the performance and user experience of the website can be greatly improved.

Ten: Compress and merge js and css files: Compress and merge some js and css files of the same type to reduce file size, thereby reducing the number of requests and improving page loading speed.

Compressing js and css files can reduce the file size, thereby reducing the overhead of network transmission. There are two commonly used compression methods: one is to delete useless characters such as spaces, newlines, and comments in the code, thereby reducing the file size; the other is to use a compression algorithm to compress the code, thereby further reducing the file size. file size. Commonly used js and css file compression tools include UglifyJS, YUI Compressor, Google Closure Compiler, etc.

The configuration of these front-end CDN optimization schemes can be adjusted and optimized according to specific situations to achieve the best results.