1 optimizing CSS

1.1 Avoid USING CSS expressions

Using CSS expressions to dynamically set CSS properties is a powerful and dangerous way to do so. Supported since IE5, but not recommended since IE8. For example, you can use CSS expressions to set the background color to alternate by the hour

  • Minimize the use of label selectors
  • Use less ID selectors and more style selectors (versatility)
  • Reduce the selector prefix, for example. Headerbox.nav. left a{} the selector is queried from right to left
  • Avoid USING CSS expressions
background-color: expression((new Date()).getHours() % 2? "#B8D4FF":"#F08A00");Copy the code

1.2 Reduce redundant code in pages

Maximize method reuse: “Low coupling, high cohesion”

1.3 Disabling @import

One of the best practices mentioned earlier is that CSS should be at the top for step-by-step rendering. Using @import in IE has the same effect as using at the bottom, so it’s best not to use it.

1.4 Avoid using filters

IE’s proprietary AlphaImageLoader filter can be used to fix translucent PNG images in previous versions of IE7. This filter blocks the render during image loading, jams the browser, increases memory consumption and is applied to every element, not every image, so there are a lot of problems. The best thing to do is not to use AlphaImageLoader at all, and gracefully downgrade to PNG8 images instead, which are well supported in IE. If you must use AlphaImageLoader, you should use the underscore hack: _filter to avoid affecting users of IE7 and later.

1.5 Put style sheets at the top

Placing the stylesheet in the HEAD section of the document makes the page seem to load faster. This is because placing the style sheet in head allows the page to gradually render. Performance focused front-end engineers want pages rendered progressively. That said, we want the browser to display the content as quickly as possible, which is especially important when there’s a lot of content on the page or when the user’s Internet speed is slow. The importance of showing users feedback (such as progress metrics) has been studied extensively and documented. In our case, the HTML page is the progress indicator! When the browser gradually loads the header, navigation bar, top logo, etc., these are taken as feedback by the user waiting for the page to load and improve the overall user experience.

1.6 compressed CSS

  • Use an online site for compression
  • Use htML-minifier to compress the CSS in HTML
  • Clean-css is used to compress the CSS
  • Webpack, gulP packaging tool

2. Image Optimization

2.1 Image Format

Try converting GIF to PNG to see if you save space. Run PngCrush (or any other PNG optimization tool) on all PNG images

2.2 Optimize CSS Sprite

The use of CSS Sprit (CSS sprit/ CSS picture wizard) technology, some of the small picture merged in a large picture above, when using, through Beijing picture positioning, positioning to a specific small picture

  • Horizontal layouts in Sprite images are generally smaller than vertical final files
  • Combining similar colors in Sprite images can keep the color count low, ideally in PNG8 format below 256 colors
  • Be “mobile-friendly” and don’t leave too much space in Sprite images. While it does not significantly affect the size of the image file, doing so saves the memory consumed by the user agent when unpacking the image into a pixel map. A 100×100 image is 10,000 pixels, and a 1000×1000 image is a million pixels.
.pubBg{ background:url('.. /img/sprit.png') no-repeat; background-size:x y; }. Box {background-position:x y; // Through the background positioning, positioning to a specific position, display different pictures geek}Copy the code

Page can not send an HTTP request, all need to complete the request + response to the complete HTTP transaction, will consume some time, may also lead to HTTP link channel blockage, in order to improve the loading speed and performance of the page, we should reduce the number of HTTP requests and reduce the size of the request content.

2.3 Image Mapping

You can combine multiple images into a single image of the same total size, but reduce the number of requests and speed up page loading. Image maps are only useful when images are contiguous on a page, such as navigation bars. Setting coordinates for an Image map is tedious and error-prone, and navigation with an Image map is not easy, so it is not recommended.

2.4 Inline images (Base64 encoded)

Use the Data: URL pattern to embed images on a page. This increases the size of the HTML file, putting inline images in a (cached) stylesheet is a good idea, and successfully prevents the page from becoming “heavy.” However, inline images are not well supported by mainstream browsers. Reducing the number of HTTP requests to a page is a starting point, and an important guideline for improving the speed of first visits to your site.

2.5 Do not zoom images with HTML

Don’t use unnecessarily large images just because you can set the width and height in HTML. If you need

<img width="100" height="100" src="mycat.jpg" alt="My Cat" />
Copy the code

The image itself (mycat.jpg) should be 100x100px, not 500x500px.

2.6 With small cacheable Favicon.ico (P.S. favorites icon)

Favicon. ico is an image placed at the root of the server, and it causes a lot of trouble because browsers automatically request it even if you leave it alone, so it’s best Not to give a 404 Not Found response. And as long as it’s on the same server, cookies will be sent every time it’s requested, plus the image will interfere with the download order, for example in IE when you request additional components in onLoad, favicon will be downloaded first. So to mitigate the disadvantages of Favicon.ico, make sure that:

  • Small enough, preferably under 1K
  • Set the appropriate expiration HTTP header (you cannot rename it later if you want to change it). It is generally safe to set the expiration date to a few months later, and you can ensure that the change is known to the browser by checking the last modified date of the current favicon.ico.

2.7 the compressed image

  • Using snowflakes

    • Use the snowflake map www.spritecow.com/
  • Using vector diagrams

    • Using vector fonts fontawesome.dashgame.com/
    • Use ali Vector Gallery www.iconfont.cn/
    • Use the vector image to convert to the font icomon.io /
  • Use base64 conversions
  • Using site compression

    • Use lossless compression tinypng.com/
    • PNG conversion webp zhitu.isux.us/
  • Use format images wisely

    • JPG lossy compression, compression rate, do not support transparency
    • PNG supports transparency and is compatible with browsers
    • Webp compression is better, and there are compatibility issues in ios WebView
    • SVG vector diagrams, code embedded, relatively small, image style relatively simple scenes

Some browser compatibility issues arise when using WebP

function checkWebp() {

    try{

        return (document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') = =0);

       }catch(err) {

        return false; }} $(document).ready(function() {

        var webp_good = checkWebp();

        if(webp_good == false) {$('img').each(function() {

            var src = $(this).attr('src');

            if(typeofsrc ! ='undefined') {

                src = src.replace('/format,webp'.'/format,jpg'); // Convert webP format to JPG format

                $(this).attr('src', src);

            }

            var original = $(this).attr('original');        // For lazy loading

            if(typeoforiginal ! ='undefined') {

                original = original.replace('/format,webp'.'/format,jpg'); // Convert webP format to JPG format

                $(this).attr('original', original); }})}})Copy the code

2.8 Image lazy loading

By adopting the technology of image lazy loading, at the beginning of the page load time, do not request the real picture address, but a default diagram when the page loading is completed, in accordance with the relevant conditions in order to load the real picture (to reduce page load for the first time the number of HTTP requests) in real project, we began to image is not loaded, page loaded for the first time, Load the images you see on the first screen, and as the page scrolls, load the images that can be displayed in the following area

  • According to the image lazy loading technology, we can also expand the data lazy loading

When loading the page, we only request the data of the first screen or the first two screens from the server (some websites render the data of the first screen in the background and return it to the client as a whole).

  • When the page is pulled down and scrolled to an area, the data required by the area is requested (request back data binding and image lazy loading, etc.).
  • Data paging display technology adoption is lazy loading thought: if we begin to request access to data is a lot of data, the partial request, we’d better start request only the first page of the data, when the page click on the second page (microblogging is next to a certain distance, to request the second page data) when the request to the second page of data.

3 optimized js

3.1 Removing duplicate scripts

Pages containing duplicate script files can affect performance, which is not what you might expect. In a review of the top 10 U.S. Web sites, only two were found to contain duplicate scripts. Two main reasons increase the chances of repeated scripts on a single page: team size and number of scripts. In this case, repeating scripts can create unnecessary HTTP requests, execute useless JavaScript code, and affect page performance. IE makes unnecessary HTTP requests, while Firefox does not. In IE, if a non-cacheable external script is introduced twice by a page, it will generate two HTTP requests when the page loads. Even if the script is cacheable, additional HTTP requests are generated when the user reloads the page. In addition to generating meaningless HTTP requests, multiple script evaluations can be a waste of time. This is because redundant JavaScript code is executed in Firefox and IE, whether the script is cacheable or not. One way to avoid accidentally introducing the same script twice is to implement a script management module in a template system. A typical way to introduce scripts is to put a SCRIPT tag in an HTML page:

<script type="text/javascript" src="Menu_1. 0.17 js." "></script>
Copy the code

3.2 Minimize DOM access

A complex page means more bytes to download, and accessing the DOM with JavaScript is slower. For example, there is a difference between looping over 500 DOM elements on a page and 5,000 DOM elements when you want to add an event handler. Disadvantages of manipulating the DOM

  • Dom exists mapping in the mechanism (DOM element object in JS and dom structure in the page is a mapping mechanism, a change is changed), this mapping mechanism, is the browser Android W3C standard to complete the construction of JS language and DOM construction (in fact, is to build a listening mechanism), dom operation is colleagues modify two addresses, Relative to some other JS programming is a performance drain.
  • Changes in the DOM structure or style of a page trigger browser backflow (the browser reevaluates the DOM structure, which can be a costly operation) and redraw (rerendering an element’s style).

When doing DOM event binding, avoid event binding one by one as far as possible, and use higher performance event delegate to achieve

Event delegate (event broker) is the top of the time board to the outer container, when the behavior of the descendant elements in the outer container is punished, the method bound to the outer container will also be triggered to execute (bubble propagation mechanism caused by), through which event source, we can do different operations

Accessing DOM elements in JavaScript is slow, so to make the page more responsive, you should:

  • Caches the index of the element that has been accessed
  • Nodes are updated “offline” and then added to the DOM tree
  • Avoid fixing layout problems with JavaScript

The number of DOM elements is easy to test by entering in the console

document.getElementsByTagName(The '*').length
Copy the code

3.3 Use intelligent event handlers

The page sometimes feels insensitive because there are too many frequently executing event handlers added to different elements of the DOM tree, which is why the use of event delegates is recommended. If you have 10 buttons in a div, you should only add one event handler to the div container, not one for each button. Events can bubble, so you can capture events and know which button is the event source.

3.4 Compiling more Asynchronous Operations

  • Synchronous programming will lead to: the above things can not be finished, the following tasks can not be done, when we develop, we can set a certain area module for asynchronous programming, so that as long as there is no necessary sequence between modules, can be loaded independently, will not be affected by the blocking of the above modules (not much use)
  • Ajax data requests, in particular, tend to be asynchronous programming, and it’s best to manage ajax requests based on the Promise design pattern (fetch, Vue, AXIos, etc., are often used in projects), because these plug-ins encapsulate Ajax based on the Promise design pattern
  • In a real project, we would try to avoid looping too much data at once (because looping is synchronous programming), especially to avoid the while loop

Avoid eval in 3.5JS

  • High performance consumption
  • After code compression, it is easy to appear the problem of code execution disorder

Minimize the use of closures in 3.6JS

  • Closures form an indestructible stack memory, and too much stack memory accumulates that affects page performance
  • It can also easily lead to memory leaks
  • Closures have their own advantages: preservation and protection, which we can only minimize, but cannot avoid

3.7 Use CSS3 motion instead of JS animation as much as possible

Css3 animation or deformation are turned on hardware acceleration, better performance than JS animation

3.8 Cache processing

For infrequently updated data, it is best to use the browser’s 304 cache for processing. For example: The first time a CSS and JS drop down request is made, the browser will cache the requested content. If 304 is done, the user will request the CSS and JS directly from the cache again. No need to fetch it from the server (reducing the number of HTTP requests). When the user forces a page refresh (CTRL + F5) or changes the CSS or JS currently cached, it is pulled from the server. For the client, we can also do some local storage based on localStronge. For example: the first requested data or the CSS and JS that are not updated frequently, we can store the content locally, the next page load, we can get from the local, we set a certain period of time or some identifier, can control at a certain stage to get from the server again

3.9 Design Mode

Write JS code as far as possible to use the design pattern to build the system, convenient later maintenance, but also improve the expansion of the

3.10 Put the script at the bottom

Scripts block concurrent downloads. The HTTP/1.1 document recommends that browsers do not allow more than two concurrent downloads per host name, or more than two if images come from multiple host names. If the script is being downloaded, the browser does not start any other downloading tasks, even if it is under a different host name. Sometimes, it’s not easy to move scripts to the bottom. For example, if the script is inserted into the content of the page with Document.write, there is no way to move it down. There may also be scope issues, which in most cases are solvable. A common recommendation is to use deferred scripts. Scripts with the DEFER attribute mean that document.write cannot be included and prompt the browser to tell them they can continue rendering. Unfortunately, Firefox does not support the DEFER attribute. In IE, scripts can be delayed, but not to the satisfaction. If the script can be deferred, we can put it at the bottom of the page and the page loads faster.

3.11 compressed js

  • Use an online site for compression
  • Use htML-minifier to compress the CSS in HTML
  • Use Uglifjs2 to compress JS
  • Webpack, gulP packaging tool

HTML 4 optimization

4.1 Audio or Video Labels

If audio or video tags appear in a page, it is best to set their preload=: The audio and video resources are not loaded when the page is loading, and start loading when the page is playing (reducing the number of times the page loads HTTP requests for the first time).

  • Preload =auto Loads the audio resource the first time the page loads
  • Preload = When the metadata page is first loaded, only the header information of the audio visual resource is loaded

4.2 Use iframe less

You can use iframe to insert an HTML document into a parent document. It’s important to understand how iframe works and use it efficiently. Advantages of

  • Introduce slow third-party content, such as logos and ads
  • Security sandbox
  • Download scripts in parallel

Disadvantages of

  • Expensive, even for a blank iframe
  • Blocking page loading
  • The semantic

4.3 put an end to 404

HTTP requests are expensive, and there is no need for an HTTP request to get a useless response (such as a 404 Not Found), which slows down the user experience without any benefit. Some sites use a helpful 404 — “Do you mean XXX?” This is good for the user experience, but also wastes server resources (such as databases, etc.). The worst thing is that the external JavaScript you link to has an error and the result is 404. First, this type of download blocks parallel downloads. Second, the browser tries to parse the body of the 404 response because it’s JavaScript code and needs to figure out what’s available in it.

5 mobile terminal

5.1 Ensure that all components are smaller than 25K

This limitation is due to the fact that the iPhone cannot cache components larger than 25K, which is the uncompressed size. That’s why curtailing content itself is important, as gZIP alone may not be enough.

5.2 Package components into a composite document

Packaged into a composite document like E-mail with attachments, multiple components can be retrieved with a single HTTP request (remember: HTTP requests are expensive). When using this approach, check to see if the user agent supports it (iPhone doesn’t).

6 cookie

6.1 Give Cookie weight loss

Cookies are used for many reasons, such as authorization and personalization. Cookie information in the HTTP header is exchanged between the Web server and the browser. It is important to keep cookies as small as possible to minimize the impact on user response time.

  • Clear unnecessary cookies
  • Keep cookies as small as possible to minimize the impact on user response time
  • Be careful to set the cookie to an appropriate domain level so as not to affect other subdomains
  • Setting an appropriate expiration date, an earlier expiration date or None can remove cookies faster and improve user response time

6.2 Place components in cookie-free fields

When the browser sends a request for a static image, cookies are sent along, and the server doesn’t need them at all. So they just cause meaningless network traffic, and you should ensure that requests to static components do not include cookies. You can create a subdomain where all static components are deployed. If the domain name is www.example.org, you can deploy static components to static.example.org. However, if cookies have been set in the top-level domain example.org or www.example.org, then all requests to Static.example.org will contain these cookies. You can buy a new domain name, deploy all the static components, and keep the new domain name cookie free. Yahoo! Yimg.com, YouTube ytimg.com, Amazon images-Amazon.com, and so on. Another benefit of deploying static components in cookie-free domains is that some proxies may refuse to cache components with cookies. One caveat: If you don’t know whether to use example.org or www.example.org as the home page, consider the impact of cookies. If you omit WWW, you can only write cookies to *.example.org, so for performance reasons it is best to use the WWW subfield and write cookies to that subfield.

7 server

7.1 Gzip components

Front-end engineers can find ways to significantly reduce the time it takes to send HTTP requests and responses over the network. Of course, the bandwidth speed of the end user, the isp, the distance of the peer exchange point, etc., are all beyond the control of the development team. But there are other factors that can affect response time. Compression can reduce response time by reducing the size of HTTP responses. Since HTTP/1.1, Web clients have had accept-Encoding HTTP request headers that support compression.

1 Accept-Encoding: gzip, deflate

If the Web server sees the request header, it compresses the response in a way that the client lists. The Web server notifys the client with the content-encoding header.

1 Content-Encoding: gzip

Using gzip compression as much as possible can reduce the weight of a page, and it’s the easiest way to improve the user experience.

7.2 Avoid leaving the SRC attribute blank

An Image with an empty string SRC attribute is a common Image, which takes two forms:

  1. straight HTML

  2. JavaScript

  3. var img = new Image(); . Img SRC = “”;

Both forms cause the same problem: the browser sends another request to the server.

7.3 configuration ETags

Entity tags (ETags) are a mechanism used by the server and the browser to determine whether components in the browser cache match components in the source server (” entities “are components: images, scripts, style sheets, and so on). Adding ETags provides an entity validation mechanism that is more flexible than the last modified date. An ETag is a string that acts as a unique identifier for a specific version of a component. The only format constraint is that the string must be enclosed in quotes, and the source server specifies the component’s ETag with the ETag in the corresponding header:

1

2

3

4
HTTP / 1.1 200 OK

``Last-Modified: Tue, 12 Dec 2006 03:03:59 GMT

``ETag: "10c24bc-4ab-457e1c1f"

``Content-Length: 12195

Then, If the browser has to validate a component, it uses the if-none-match request header to pass the ETag back to the source server. If the ETags match is successful, a 304 status code is returned, reducing the response body by 12,195 bytes. GET/I /yahoo.gif HTTP/1.1 Host: us.yimg.com if-modified-since: Tue, 12 Dec 2006 03:03:59 GMT if-none-match: “10C24BC-4AB-457E1C1f” HTTP/1.1 304 Not Modified ** **

7.4 Using GET Requests for Ajax

The mailbox team found that with XMLHttpRequest, a browser POST request is implemented through a two-step process: send the HTTP header first, then send the data. So it’s best to use a GET request, which only needs to send a TCP packet (unless there are a lot of cookies). The maximum URL length of IE is 2K, so you can’t use GET if you want to send more than 2K data. An interesting side effect of a POST request is that no data is actually sent, just like a GET request. As described in the HTTP documentation, GET requests are used to retrieve information. So its semantics are only to use GET requests to request data, not to send data that needs to be stored on the server.

7.5 Clear the buffer as soon as possible

When a user requests a page, the server takes about 200 to 500 milliseconds to assemble the HTML page while the browser waits for the data to arrive. PHP has a flush() function that allows the browser to send a portion of the HTML response that is already ready so that the browser can start retrieving components while the rest is ready in the background, the main benefit being on busy backgrounds or very “light” front pages (P.S. In other words, response time is most advantageous when it is primarily in the background). The ideal place to clear the buffer is after the HEAD, because the HEAD portion of HTML is generally easier to generate and allows the introduction of any CSS and JavaScript files, allowing the browser to start fetching components in parallel while the background is still processing. Such as:

&emsp;<br />.<! -- css, js --><br />    </head><br /> <? php flush(); ? ><br /> <body><br /> ... <! -- content --><br />Copy the code

7.6 Using CDN (Content Delivery Network)

The physical distance between the user and the server also has an impact on response time. Deploying content on multiple geographically dispersed servers allows users to load pages faster. But how? The first step to geographically dispersed content is: Don’t try to redesign your Web application to accommodate a distributed structure. Depending on the application, changing the structure can involve daunting tasks such as synchronizing session state and replicating database transactions across servers (translation may be inaccurate). Proposals to reduce the distance between users and content can be delayed or impossible because of this conundrum. Remember that 80% to 90% of the end user’s response time is spent downloading page components: images, styles, scripts, Flash, etc. This is the golden rule of performance. It is better to disperse the static content rather than redesign the application structure from the start. This not only significantly reduces response time, but also makes it easier to show credit for CDN. A Content delivery network (CDN) is a group of geographically dispersed Web servers that deliver content to users more efficiently. Typically, the server chosen to send the content is based on a measure of network distance. For example, select the server with the least hops or the fastest response time.

7.7 Add the Expires or cache-control HTTP header

This rule has two aspects:

  • For static components: by setting a distant future time asExpiresTo never fail
  • Redundant dynamic components: use appropriate onesCache-ControlHTTP headers to allow the browser to make conditional requests

Web design is getting richer, which means pages have more scripts, images and Flash. New visitors to the site may still have to submit several HTTP requests, but by using expiration dates you can make the component cacheable, which avoids unnecessary HTTP requests during subsequent browsing. Expiration HTTP headers are usually used for images, but they should be used for all components, including scripts, styles, and Flash components. Browsers (and proxies) use caching to reduce the number and size of HTTP requests and make pages load faster. The Web server uses the expiration HTTP response header to tell the client how long the various components of the page should be cached. Using a date in the distant future tells the browser that the response will not change until April 15, 2010.

1 Expires: Thu, 15 Apr 2010 20:00:00 GMT

If you are using an Apache server, use the ExpiresDefault directive to set the expiration date relative to the current date. The following example sets a validity period of 10 years from the request time: ExpiresDefault “Access Plus 10 years”

7.8 Reducing DNS Queries

The domain name system establishes a mapping between host names and IP addresses, just as people and numbers are mapped in a phone book. When you type www.shanghai70.com into your browser, the browser will contact the DNS resolver to return the server’s IP address. DNS has a cost. It takes 20 to 120 milliseconds to find the IP address for a given host name. The browser cannot download anything from the host name until the DNS lookup is complete. DNS lookups are cached more efficiently, stored on a special caching server by the user’s ISP or local network, but can also be cached on individual users’ computers. DNS information is stored in the OPERATING system’s DNS cache(DNS client service on Microsoft Windows). Most browsers have their own cache independent of the operating system. As long as the browser keeps this record in its cache, it will not query the operating system for DNS. IE caches DNS lookups for 30 minutes by default, written in the DnsCacheTimeout registry setting. The Firefox cache for 1 minute, you can use the network. DnsCacheExpiration configuration Settings. If the client’s DNS cache is empty (both browser and OS), the number of DNS lookups is equal to the number of different host names on the page, including page urls, images, script files, Host names in stylesheets, Flash objects, and so on, reduce DNS lookups by reducing the number of different host names. Reducing the number of different host names also reduces the number of components a page can download in parallel, avoiding DNS lookups reduces response time, while reducing the number of parallel downloads increases response time. My rule is to spread components out between 2 and 4 host names, which is a compromise between reducing DNS lookups and allowing high concurrent downloads.

7.9 Avoiding Redirection

The redirect uses 301 and 302 status codes, and below is an HTTP header with the 301 status code

HTTP/1.1 301 Moved Permanently Location: example.com/newuri Content-type: text/ HTML

The browser automatically jumps to the URL specified in the Location field. All the information needed for a redirect is in the HTTP header, and the response body is generally empty. Additional HTTP headers, such as Expires and cache-Control, also represent redirects. There are other ways to jump: refresh meta tags and JavaScript, but if you have to do redirection, it’s best to use the standard 3xxHTTP status code, mainly to make the back button work. Keeping in mind that redirects slow down the user experience, inserting redirects between the user and the HTML document delays everything on the page, the page can’t be rendered, and components can’t start downloading until the HTML document is delivered to the browser. One common and extremely wasteful redirection that Web developers are not aware of is when a slash is missing at the end of a URL. For example, a jump to www.shanghai70.com/a returns a 301 response redirected to www.shanghai70.com/b (note the trailing slash). In Apache you can use the Alias, mod_rewrite, or DirectorySlash directives to cancel unwanted redirects. The most common use of redirection is to connect an old site to a new site, but also to different parts of the same site, doing something for different users (browser type, user account type, and so on). Using redirects to connect two sites is the easiest and requires only a small amount of extra code. While using redirects at these times reduces the developer’s development complexity, it reduces the user experience. One alternative is to use Alias and mod_rewrite, provided both code paths are on the same server. If you used redirects because of a domain name change, you can create a CNAME (create a DNS record pointing to another domain name as an Alias) combined with the Alias or mod_rewrite directive.

7.10 Transfer in Json Format

In the data communication between the client and server, we try to use JSON format for data transmission

  • The data in JSON format can clearly show the data structure, and it is also convenient for us to obtain the operation
  • Data in JSON format is much more lightweight than the XML format transport of old
  • Both client and server support json format data processing, processing is very convenient

In real projects: Not all data is JSON-based, we try to do this, but for some specific needs (such as file stream transfer or document transfer) json is not appropriate