Front-end resources are huge, including HTML, CSS, JavaScript, Image, Flash, Media, Font, Doc and so on. Front-end optimization is relatively complex, and there are different ways to optimize various resources. According to granularity, it can be roughly divided into two categories, the first is page-level optimization. For example, reducing the number of HTTP requests, non-blocking loading of scripts, location optimization of inline scripts, etc. The second type of optimization is code-level optimization, such as DOM manipulation optimization in JavaScript, image optimization and HTML structure optimization, etc. Front-end optimization from the user perspective can make the page load faster, respond to the user’s operation in a more timely manner, and provide users with a more friendly experience. Front-end optimization from the service provider perspective can reduce the number of page requests, reduce the bandwidth occupied by requests, and save server resources

Reducing HTTP requests

Most of the loading time of the front-end is to download various resources. The browser has a limited number of HTTP request connection pool for the same server. Excessive requests need to be queued. It also avoids the time consumption caused by too many TCP handshakes during HTTP connections

  • CSS Sprite, also known as Sprite, can reduce the number of images by combining multiple images into one image. In addition, because the merged images are relatively separate images, it reduces the storage cost of information such as color tables and format information. The combined image size tends to be smaller than the sum of the separate images, although the combined image size tends to be larger if there is a lot of white space to separate the original individual images. To use Sprite images, use CSS backgroud-Image and background-position properties to display the desired image segments

  • Image maps are a good choice if your website has many linked images, such as maps, etc. Image maps allow you to have many linked images on a single Image.

    and

    are used to divide a complete image map into multiple regions to make different links, which can also reduce the number of HTTP request links for the image

  • Inline images embed image data directly into a page or CSS using the data:URL scheme, which increases the size of a document or CSS file, but also reduces the number of HTTP requests. For data: the URL format is data:[

    ][;base64],

  • Font icon uses Font ICONS instead of ICONS. Combining multiple ICONS into Font ICONS can not only reduce the number of HTTP requests for pictures and the size of ICONS, but also avoid distortion for zoom in and out operations as vector images. In addition, the advantages of Font ICONS include easy color change, shadow, transparent effect, etc. CSS is well supported for various styles, rotations and animations

  • Combining multiple CSS or JavaScript files into a single CSS or JavaScript file can reduce the number of HTTP requests. The file size can also be reduced through compression algorithms. Composite files can become difficult to read and modify as scripts and stylesheets change from page to page, but making them part of the publishing process can shorten the time

Leverage caching

  • Cache Control sets resource component expiration time and expiration policy by setting Expires and cache-control in response header on the server side. For static resources, it can set Expires to a long-term time to achieve the policy of never expiration. For dynamic components, cache-control specifies a caching mechanism to assist the browser in processing condition I requests

  • External references set JavaScript and CSS to be imported from external files rather than embedded directly into HTML. Due to the browser’s caching mechanism, external files can be imported from the browser’s cache without having to request the same resource file repeatedly for each request. This makes the browser open the page much faster the second time. Of course, bringing in all external files increases the number of HTTP requests, so the key issue with external imports is how to weigh the number of external JavaScript and CSS files cached against the number of HTML documents, which is difficult to quantify, but can be measured using various metrics. When users on a site have multiple page views per session, and many pages use the same scripts and stylesheets, the potential benefits of caching external files are greater

Optimizing resource loading

  • Introducing or embedding CSS in , depending on the order in which the browser renders, can make pages render faster than placing CSS in or at the bottom of the page, which is important on rich web sites or when the Internet connection is slow. If the style sheet is placed at the bottom, it will cause the browser to start rendering the page before the style sheet is loaded, and the page cannot be rendered gradually and immediately jumps from the no style state to the style state, and the user experience will be poor. In addition, some browsers may render the page after the CSS has been downloaded, resulting in a delay in page rendering

  • The browser can make concurrent requests, which makes it faster to load resources. However, the imported JavaScript script blocks other resources during loading. For example, images, styles, and other scripts behind the script are blocked before the script is loaded. Loading will not start until the script is loaded. One of the reasons is that Js may change the page or dependencies between Js. For example, A. Js changes the page with Document. write, and B. Js relies on A. Js. Therefore, the order must be strictly guaranteed, not parallel download. If the script is placed before the comparison, it will affect the loading speed of the entire page and thus the user experience. In addition, when the browser finds a Js script, the browser will immediately start parsing the script and stop parsing the document, because the script may change the DOM and CSS, and continuing parsing will waste resources. There are many ways to solve these problems, such as asynchronously loading scripts, and the simplest and most reliable method is to move the script as far back as possible to reduce the impact of concurrent downloading and page rendering

Optimized code scheme

  • Avoid CSS expressions. CSS expressions accept JavaScript expressions through the expression method, which is a powerful but dangerous way to set up CSS dynamically. The problem with CSS expressions is that they are evaluated frequently, and CSS is evaluated much more often than we think. Not only is it computed when the page is displayed and indented, but it is recalculated when scrolling or moving the mouse, affecting the performance of the page. Properties can be evaluated and assigned to style properties, which are one-time expressions, using Js, and if style properties must be set dynamically throughout the life of the page, you can use event handlers instead of CSS expressions. If you must use CSS expressions, be aware that they can be evaluated thousands of times, and can potentially affect page performance

  • Avoid redirects. Avoid redirects. When a page is redirected, it delays the transfer of the entire HTML document. Nothing is rendered on the page until the HTML document arrives, and no components are downloaded, degrading the user experience. If you must use redirects, such as HTTP to HTTPS, use 301 permanent redirects instead of 302 temporary redirects. Because if you use 302, every time you visit HTTP, you’re redirected to an HTTPS page, and a permanent redirect is remembered by the browser after the first HTTP to HTTP redirect, and every time you visit HTTP, you’re directly returned to the HTTPS page

  • DOM minimization JavaScript DOM manipulation inevitably triggers redrawing or rewinding of the browser. Since redrawing and rewinding can be expensive, it is best to reduce the number of times it is sent. To reduce the number of times it is sent, we can combine the DOM and style changes several times and then dispose of them all at once. Or the style implementation can be designed to dynamically change the class. Or we can modify DOM offline by using the documentFragment object to manipulate DOM in memory. DOM modification in memory is to separate elements from the document flow without triggering redrawing. After modification, the node is put into the document flow again and only one backflow is triggered

Compressed resource files

  • Gzip starts with HTTP/1.1, and clients can indicate support for compression by using accept-Encoding: Gzip, deflate in HTTP requests. If the server sees this header in the request, it can compress the response using one of the methods listed by the client, and the server informs the client of gZIP compression through Content-Encoding:gzip in the response. Gzip is the most popular and efficient compression method, developed by the GNU Project and standardized by RFC 1952

  • Compress JavaScript and CSS files to reduce their size by removing unnecessary characters from the code, thereby reducing load time. When the code is minimized, all comments and unwanted whitespace characters are removed, resulting in improved response time performance due to the reduced size of the downloaded files

Optimizing network requests

  • CDN the full name of CDN is Content Delivery Network. CDN is an intelligent virtual Network built on the basis of the existing Network, relying on edge servers deployed in various places, through load balancing, Content distribution, scheduling and other functional modules of the central platform. Users can obtain the required content nearby, reducing network congestion and improving user access response speed and hit ratio. When users are in multiple locations across regions, they have different perceptions of the response speed of the server. Most of the time when users visit the website is in the state of downloading static resources. Distributing these static resources to each CDN server first can greatly shorten the response time. CDN can select the server with the least number of network hops or the server with the fastest response according to the user’s network status information to load the resources needed by the user nearby

  • DNS pre-resolution When the browser accesses a domain name, it needs to resolve the DNS to obtain the IP address of the domain name. In the process of parsing, the cache is read step by step in the order of browser cache, system cache, router cache, ISP(carrier)“““DNS cache, root DNS server, TOP-LEVEL DNS server, and primary DNS server until the IP address, DNS Prefetch, That is, DNS pre-resolution is to resolve the domain names that may be used after the resolution according to the rules defined by the browser, so that the resolution results are cached in the system cache, shortening the DNS resolution time, and improving the access speed of websites

    <link rel="dns-prefecth" href="https://www.google.com">
    <link rel="dns-prefech" href="https://www.google-analytics.com">
    Copy the code

    Resolving DNS ahead of time, because it is parallel, does not clog page rendering, which can shorten resource loading time

  • Configure ETag Entity Tag ETag is a mechanism used by Web servers and browsers to determine whether the resource in the browser cache matches the resource on the original server. ETag was added to provide a more flexible mechanism for validating entities than the last modified date. An Etag is a string that uniquely identifies a particular version of a component. The only format restriction is that it is enclosed in quotes. The original server uses the Etag response header to specify the Etag of the component

  • Release the buffer early When a user requests a page, it can take 200 to 500 milliseconds for the back end server to stitch together the HTML page, during which time the browser is idle while waiting for the data to arrive, allowing the server to send the processed data to the front end. Cause the browser to start loading external resources first. With PHP, for example, you can use the function Flush () to send a partially ready HTML response to the browser so that the browser can start retrieving resources while the back end is busy processing the rest of the HTML page, with the main benefits being a busy back end or a lightweight front end