Location>code7788 >text

Front-end performance optimization practice directions and methods

Popularity:355 ℃/2024-07-26 16:09:15

0x01 Code Optimization and Compression

(1)HTML

Remove unnecessary whitespace characters, comments and redundant tags to reduce file size

  1. Using commandsnpm install html-minifier -g mountingHTML Minifier

  2. Using Commandshtml-minifier -V Confirm successful installation

  3. Configuration in the environment

    // pull into HTML Minifier
    const minify = require("html-minifier").minify;
    
    // deal with HTML copies
    let result = minify('<p title="blah" id="moo">foo</p>', {
      removeAttributeQuotes: true,
    });
    
    // 输出deal with结果
    (result);
    
  4. Using Commandsnode .\ Run it and the output will be:<p title=blah id=moo>foo</p>

  5. Detailed reference:/package/html-minifier
    Online use:/html-minifier/

(2)CSS

Streamline stylesheets, avoid redundant or obsolete properties, and organize selectors wisely to reduce computational complexity

  1. Using Commandsnpm install cssnano postcss postcss-cli --save-dev Installing PostCSS with CSSNaNo

  2. Configuration in the environment

     = {
      plugins: [
        require("cssnano")({
          preset: "default",
        }),
      ],
    };
    
  3. Using Commandsnpx postcss > Run to generate optimized results

  4. Detailed reference:/docs/introduction/

  5. Other tools:

    1. PostCSS:/
    2. PurgeCSS:/

(3)JavaScript

Compress code using tools (such as Webpack, etc.) or online services to remove spaces, comments, and unnecessary characters

  1. Using Commandsnpm install terser-webpack-plugin --save-dev Install terser-webpack-plugin

  2. Configuration in the environment

    const TerserPlugin = require("terser-webpack-plugin");
    
     = {
      optimization: {
        minimize: true,
        minimizer: [new TerserPlugin()],
      },
    };
    
  3. Using Commandsnpx webpack Run Webpack and optimize your JavaScript code.

(4) Consolidation of documents

Reduce the number of HTTP requests by combining multiple CSS and JavaScript files into one.

  • In Webpack, you can configure theentry respond in singingoutput option to automatically merge multiple modules into a single file.
  • In Gulp, you can use thegulp-concat Plugin to merge files

0x02 Static Resource Optimization

(1) Compression of images

  • TinyPNG:API Reference
  • ImageOptim:Optimize on the fly
  • imagemin:/package/imagemin

(2) Lazy loading of images

a. Native JavaScript

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" /> <style>
  <style>
    img {
      width: 1000px;
      width: 1000px; height: 700px;
      background-color: wheat;
      
      object-position: center; }
    }
  </style>.
</head>.

<body>.
  <img src="" data-src=". /images/" alt="" /> <img src="" data-src=".
  <img src="" data-src=". /images/" alt="" /> <img src="" data-src=".
  <img src="" data-src=". /images/" alt="" /> <img src="" data-src=".
  <img src="" data-src=". /images/" alt="" /> <img src="" data-src=".
  <img src="" data-src=". /images/" alt="" /> <img src="" data-src=".
  <script>
    /**
     * Initialize the lazy image loading function.
     * This function implements lazy loading of images by listening to the window's scroll event. When the image enters the viewport, set its src attribute to the real image source URL, thus realizing the lazy loading effect.
     */
    const imageLazyLoad = () => {
      // Get all the image elements on the page with the data-src attribute
      const imgs = ("img");
      // Define a calc function to check if the image is in the viewport or not
      const calc = () => {
        ((img) => {
          // Check if the image is in the viewport: if the top position of the image is less than or equal to the bottom position of the window, then the image is in the viewport and can be loaded
          if ( <= + )
            // Set the image's src attribute to the value of the data-src attribute to actually start loading the image
             = ;
          else
            // If the image is not in the viewport, return without loading it
            return;
        });
      }; // Listen to the window's scroll event to trigger the loading of the image on scrolling.
      // Listen to the window's scroll event to trigger the loading of the image on scrolling
      ("scroll", () => calc()); // Listen to the window's scroll event to trigger the loading of the image when it is scrolled.
      // Calculate and load the image in the visual area as soon as the page loads for the first time.
      calc();
    };
    // Call the function to initialize lazy loading of images
    imageLazyLoad();; // Call the function to initialize image lazy loading.
  </script>; // Call the function to initialize lazy loading of images.
</body>; // Call the function to initialize lazy loading of images.

</html>.

b. Intersection Observer API

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" /> <style>
  <style>
    img {
      width: 1000px;
      width: 1000px; height: 700px;
      background-color: wheat;
      
      object-position: center; }
    }
  </style>.
</head>.

<body>.
  <img src="" data-src=". /images/" alt="" /> <img src="" data-src=".
  <img src="" data-src=". /images/" alt="" /> <img src="" data-src=".
  <img src="" data-src=". /images/" alt="" /> <img src="" data-src=".
  <img src="" data-src=". /images/" alt="" /> <img src="" data-src=".
  <img src="" data-src=". /images/" alt="" /> <img src="" data-src=".
  <script>
    /**
     * Initialize lazy loading of images
     * This function implements lazy loading of images via the IntersectionObserver API. The image resource is only actually loaded when the image enters the viewport
     */
    const imageLazyLoad = () => {
      // Get all the image elements that need to be lazy loaded
      const imgs = ("img");

      // Create an instance of IntersectionObserver to watch for images entering the viewport
      const observer = new IntersectionObserver((entries) => {
        // Iterate over all observed entries
        ((entries) => {
          // If the image enters the viewport
          if () {
            let img = ;
            // Set the src attribute of the image to the value of the data-src attribute, the real image source address
             = ;
            // Stop watching the image as it is loaded
            (img);
          }
        });
      }).

      // Enable IntersectionObserver observation for all image elements that require lazy loading
      ((img) => {
        (img);
      });
    };
    imageLazyLoad();
  </script>
</body>

</html>.

c. Third-party repositories

  • as ifvue-lazyload(used in the Vue framework)

(3)CDN

  • Deploy content delivery networks (CDNs) to host static resources on edge nodes that are geographically close to users, reducing latency
  • Steps:
    1. Choose a CDN service provider, such as Amazon, Cloudflare, etc.
    2. Uploading static resources
    3. Configuring DNS
    4. Tested and optimized
  • Benefits: Reduces access latency, improves availability, reduces load on source servers

(4) Caching mechanism

  • Steps:
    1. Set the Cache-Control header: response header field to indicate that these resources will be loaded directly from the local cache during the cache validity period, rather than sending a request to the server
    2. Use ETag: response header field indicating a specific version of the resource
      • When the browser requests the resource again, it sends the ETag value to the server, and if the resource has not changed (i.e., the ETag value is the same), the server returns a 304 Not Modified response telling the browser to use the locally cached version.
    3. Configuring the Expires header: compatibility with older browsers
  • Benefits: reduced server load, faster loading, improved user experience

0x03 Rendering Performance Optimization

(1) Reduce the number of DOM elements

Avoid unnecessary DOM elements to reduce rendering and redrawing time

  1. Replacing DOM Elements with CSS

    Examples:

    <ul>
      <li><img src="" alt="Icon 1"><span>Item 1</span></li>
      <li><img src="" alt="Icon 2"><span>Item 2</span></li>
    </ul>
    

    optimize to

    <ul>
      <li class="item">Item 1</li>
      <li class="item">Item 2</li>
    </ul>
    
    <style>
    .item::before {
      content: "";
      display: inline-block;
      width: 20px;
      height: 20px;
      background-image: url();
      background-size: cover;
      margin-right: 5px;
    }
    </style>
    
  2. Introducing Flex Layout and Grid Layout

    Examples:

    <div class="container">
      <div class="row">
        <div class="col">Item 1</div>
        <div class="col">Item 2</div>
      </div>
    </div>
    

    optimize to

    <div style="display: flex;">
      <div>Item 1</div>
      <div>Item 2</div>
    </div>
    
  3. Multiple dynamic content is added using DocumentFragment

    Examples:

    for (let i = 0; i < 100; i++) {
      let li = ("li");
       = `Item ${i}`;
      ("ul").appendChild(li);
    }
    

    optimize to

    let fragment = ();
    for (let i = 0; i < 100; i++) {
      let li = ("li");
       = `Item ${i}`;
      (li);
    }
    ("ul").appendChild(fragment);
    

    DocumentFragment is a lightweight document object that can contain nodes and children, but will not be part of the document tree.

(2) Event Delegation

Reduce the number of interactions with the DOM and improve performance with event delegates

  • Event Delegation: a technique for event handling that utilizes theevent bubblingInstead of setting up an event listener on each child element, the parent element sets up an event listener on each child element. When an event occurs on a child element, the event bubbles up to the parent element, and the event listener on the parent element checks the source of the event (i.e., the child element that triggered the event) and performs the appropriate action accordingly

  • give an example

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8" />
    </head>
    
    <body>
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
      </ul>
      <button>Add item</button>
      <script>
        const ul = ("ul");
    
        ("click", (e) => {
          if ( === "LI") {
            ("", );
            ();
          }
        });
    
        const button = ("button");
        ("click", () => {
          const newItem = ("li");
           = `Item ${ + 1}`;
          (newItem);
        });
      </script>
    </body>
    
    </html>
    

(3) Optimize DOM operations

Reduce redraws and reflows with techniques such as batch updates, virtual DOMs, etc.

  1. batch update: combine multiple DOM operations into a single batch and execute them all at once (cf. DocumentFragment)
  2. Virtual DOM: a programming concept to represent the DOM tree as a JavaScript object.
    • When the state of the application changes, the virtual DOM tree is updated first, and then efficient algorithms (such as the diff algorithm) are used to compare the differences between the old and new virtual DOM trees and apply only those differences to the real DOM
    • That is, it detects the DOM elements that have changed and operates only on the changed DOM elements, reducing unnecessary DOM operations.
    • Generally widely used in front-end frameworks like React, Vue, etc.

(4) CSS on top

  • Place the CSS in the<head> tag to ensure that the page renders the style first when it loads

    <head>
      <link rel="stylesheet" href="" />
    </head>
    

(5) Asynchronous Loading of JavaScript

  • Place JS scripts that are not required for the first screen at the end of the document or use theasyncdefer attribute to avoid blocking the rendering

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <! -- Synchronized loading of first screen required scripts -->!
      <script src=""> </script>
    </head>
    
    <body>
      <! -- page content -->
    
      <! -- Asynchronous loading of scripts that are not on the first screen and have no dependencies -->!
      <script async src=""> </script>
    
      <! -- Non-first-screen scripts that are loaded asynchronously but executed sequentially -->
      <script defer src=""></script>
    
      <! -- Place non-first-screen scripts at the bottom (for older browsers that don't support async/defer) -->
      <! -- <script src=""> </script> -->
    </body>
    
    </html>
    
  • async together withdefer

    • Both are used to load scripts asynchronously
    • async: Fully asynchronous, the loading and execution of scripts will not block the parsing of documents, but the order of execution between multiple asynchronous scripts is not necessarily the same, and it is not recommended to use it for scripts with dependencies.
    • defer: wait until the entire document has been parsed and displayed, and then execute the scripts in the order in which they appear in the document

0x04 Network Performance Optimization

(1) Enabling HTTP/2 or HTTP/3

  • Enable HTTP/2 or HTTP/3 to improve request efficiency with features such as multiplexing, header compression, etc.
  • Typically in a web server, configured and enabled via Nginx, Apache, etc.

(2)TLS/SSL

  • Ensure that your website uses HTTPS encrypted transmissions for increased security and possible SEO advantages
  • HTTPS, TLS/SSL application reference for network transport:Browser working process and related terms | Blogspot-SRIGT

(3) Pre-loading and pre-reading

a. Preloading

  • Preload: A resource hint that tells the browser that this resource is important for the current navigation.right nowneeded and should beprioritizationDownloading and parsing

    • such as fonts, CSS and key JavaScript scripts
  • utilization<link rel="preload"> Preloading of key resources

    <head>
      <! -- Preloading fonts -->!
      <link rel="preload" href="fonts/myfont.woff2" as="font" type="font/woff2" crossorigin="anonymous">
    
      <! -- Preloading CSS -->!
      <link rel="preload" href="styles/" as="style">
    
      <! -- Other header tags... -->
    </head>
    

b. Pre-reading

  • Pre-read: a resource hint that tells the browser that this resourcelikelihoodWill be used in future navigation, but doesn't have the same urgency as preloaded

    • Browsers can choose to download these resources during idle time so that they can be loaded faster when the user actually needs them
  • utilization<link rel="prefetch"> Pre-reading of future resources that may be required

    <link rel="prefetch" href="details/">
    <link rel="prefetch" href="details/"> 
    

(4) Local Cache

  • Storage limitation: the storage size is limited to about 4KB, and the number of storage is limited.
  • Drawbacks:
    1. Carrying cookie data in the HTTP request each time may result in thePerformance issuesfurthermorebandwidth consumption
    2. Lower security
  • Due to the cross-domain limitations of browsers, the client and server must ensure the principle of same-origin
  • Scenario: tracking user session information, such as user login status, shopping cart information, etc.
  • Session: stores cached data in the server as key-value pairs and returns the key (Session ID) as a cookie to the browser
  • Token: A solution for the mobile Internet that does not provide cookies, encrypts the data hash and saves it in the mobile storage system.
    • JWT is a widely used Token standard.

b. LocalStorage

  • HTML5 provides a new local caching scheme for storing data in the user's browser.
  • Storage limitations:
    • Long-lasting, no expiration date until manually deleted or browser clears cache
    • Storage space is generally 5MB and above (varies by browser).
  • Scenario: Storing data that needs to be persisted across multiple pages or sessions, such as user preferences, game progress, etc.

c. SessionStorage

  • Roughly similar to LocalStorage, in that the storage limitations are such that the data is only valid for the duration of the current session and is cleared when the browser is closed or the tab is closed.
  • Scenario: Store data that is only needed in the current session, such as temporary status information, form data, etc.

d. IndexedDB

  • A low-level API that allows for complex querying, transaction processing, and database management operations, providing indexing functionality
  • Storage limitations: relatively large storage space, can store a large amount of data
  • Scenario: store a large amount of structured data and need to perform complex queries, such as offline applications, game data storage, etc.

e. Cache API

  • An interface for storing and retrieving responses to network requests

  • Can be used in conjunction with Service Workers for offline applications and performance optimization

    Service Workers: Scripts that run in the web browser and have the ability to run independently of the web page in the background.

    • Provides many advanced features such as offline content caching, push notifications, background data synchronization, etc.
  • Scenario: Precise control of caching policies and resource caching, e.g., when building PWAs (Progressive Web Apps)

0x05 Selection and Optimization of Frameworks and Libraries

(1) Framework

  • light-weight class (in athletics)

    • Preact: A lightweight, fast alternative to React at 3kb, with the same modern APIs.
    • Vue3: On top of Vue2, the applicationTree-shakingThe following are a few examples of the code that can be automatically removed during the build process
  • Load on Demand

    • adoptioncode segmentationrespond in singinglazy loading (computing)technology that splits the application into smaller pieces and loads them only when needed

    • Vue Router, for example, supports dynamic imports of

      const routes = [
        {
          path: "/products",
          name: "Products",
          // Lazy loading of components using dynamic imports
          component: () =>
            import(/* webpackChunkName: "products" */ "./views/"),
        },
        // Other Routes...
      ];
      

(2) Third-party libraries

  • Introduce only essential libraries, avoid obsolete or redundant libraries, and regularly check for updates to take advantage of performance optimizations

0x06 Performance Monitoring and Optimization Tools

(1) Performance analysis tools

  • Lighthouse: an open source automation tool developed by Google and integrated into Chrome DevTools
  • PageSpeed Insights: a free tool provided by Google.Official website link
  • Chrome DevTools Performance panel: integrated in Chrome DevTools

(2) User performance monitoring

Gathering load performance data from real users with an integrated RUM (Real User Monitoring) tool

  • Google Analytics: Use the plugin Google Tag Manager to deploy a RUM script that collects user interaction data and sends it to Google Analytics for processing and analysis.
  • SpeedCurve:/

0x07 Other Optimization Strategies

(1) First screen content optimization

  • Ensure that key content is displayed immediately when the first screen loads to avoid users seeing a blank or loading indicator for too long
  • Example: e-commerce website first screen optimization operation
    • Streamlining the first screen: Retain the most critical content, such as website logo, welcome message, rotating image, product recommendation.
    • Optimize images and scripts: Compress and optimize all first-screen loaded images, merge and compress CSS and JavaScript scripts to reduce the number of HTTP requests.
    • Asynchronous loading of non-critical content: Non-first-screen key content is set to load asynchronously, i.e., it is loaded when the user scrolls to the appropriate position.
    • Accelerate with CDN: Distribute website content to multiple CDN nodes around the world, selecting the nearest node to load based on the user's geographic location.
    • Preloading and caching: Utilizing the browser's preloading and caching mechanisms to load and store some commonly used resource files in advance

(2) Semanticized HTML

  • Use sensible HTML tags and their specific attributes to format document content and improve comprehensibility.

  • Detailed method reference:HTML Semantics | CSDN - Beihang Programmer Xiao Chen

  • Examples:

    <!DOCTYPE html>
    <html lang="zh-CN">
    
    <head>
      <meta charset="UTF-8"> <html lang="zh-CN"> <head>
      <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>
      <title> News article title</title>
    </head>
    
    <body>
      <header>.
        <h1> news article title</h1> </header> <body> <header> <header>.
        <p> Published by <a href="/author-profile"> author name</a> on <time datetime="2023-04-01"> April 1, 2023</time> </p>
      </header>
    
      <main>
        <article>
          <h2> introduction</h2> </header> <main> <article>.
          <p> Here is the introduction section, which briefly introduces the topic and background of the article. </p>
    
          <h2> Body headings </h2>
          <p> Here is the first paragraph of the body of the text, detailing the main idea or story of the article. </p>.
    
          <h3> subsection headings </h3>
          <p> Here is a subsection of the article that further refines or supports the main point. </p>
    
          <! -- You can continue to add more h2, h3, p, etc. to build up the content of the article -->
    
          <footer>
            <p> End of article. </p>
          </footer>
        </article>
      </main>
    
      </article> </main> <aside>
        <h2> Related Articles</h2>
        <ul>
          <li> <a href="/article1"> Related articles1</a> </li>
          <li><a href="/article2">related articles2</a></li>
          <! -- Links to more related articles -->.
        </ul>
      </aside>
    
      <footer>
        <p> All rights reserved &copy; 2023 Site Name </p>
      /footer>.
    </body>.
    
    </html>.
    

(3) Metadata

  • set up<title><meta><link rel="canonical"> Other SEO related tags

  • Examples:

    <!DOCTYPE html>
    <html lang="zh-CN">
    
    <head>.
      <! -- page encoding for strings in different languages -->
      <meta charset="UTF-8" />
    
      <! -- Setting the viewport to ensure that the page displays correctly on different devices -->.
      < meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
      <! -- Page title, displayed in browser tabs and search results -->
      <title> page title - the name of the site </title>
    
      <! -- Page description, displayed in search results, used to summarize page content -->!
      <meta name="description" content="Here is a short description of the page, which should contain keywords and entice users to click." />
    
      <! -- Page keywords, although modern search engines place less emphasis on the keywords tag, it can still be used as a reference -->!
      < meta name="keywords" content="keyword1, keyword2, keyword3" />
    
      <! -- Specifies the canonical URL of the page, which helps prevent duplicate content from being indexed by search engines -->!
      <link rel="canonical" href="/your-page-url" />
    
      <! -- Other possible metadata --> <!
      <meta name="author" content="Author's name or organization" /> <! -- Add author information -->
      <meta name="robots" content="index, follow" /> <! -- Instructs search engines to index and follow links on the page --> <!
    
      <! -- For responsive sites, meta tags can be used to adapt to different devices -->!
      < meta name="HandheldFriendly" content="true" /> <! -- Tells mobile devices that the page is suitable for mobile viewing -->
      <meta name="MobileOptimized" content="320" /> <! -- Specifies the screen width of the mobile device to accommodate responsive design --> <meta name="MobileOptimized" content="320" />!
    
      <! -- Introduces CSS styling -->!
      <link rel="stylesheet" href="" />
    </head>
    
    <body>
      <! -- page content -->
      <! -- Introducing JavaScript scripts --> <!
      <script src=""> </script>
    </body>
    
    </html>
    

(4) Structured data

  • Structured data: a way to mark up the content of a web page using a specific format (such as JSON-LD, Microdata, or RDFa) so that search engines and other machines can more easily understand and process the information

  • Example: The following is structured data in JSON-LD format.

    <!DOCTYPE html>
    <html lang="zh-CN">
    
    <head>
      <meta charset="UTF-8" />
      <title>The movie Star Trek</title>
      <script type="application/ld+json">
        {
          "@context":"/",
          
          "name": "Star Trek",
          "image":"/",
          "director": {
            "@type": "Person".
            "name": "Christopher Nolan".
          },
          "genre": ["Sci-Fi", "Drama", "Adventure" ], .
          "actor": [
            {
              "@type": "Person".
              "name": "Matthew McConaughey"
            },
            {
              "@type": "Person", "name".
              "name": "Anne Hathaway"
            }
          ], { "@type": "Person", "name": "Anne Hathaway" }
          "datePublished": "2014-11-07",
          "description": "The story of a team of explorers who use their new discovery against wormholes to go beyond humanity's limits for space travel, thus embarking on an interstellar voyage through the vast universe." ,
          "aggregateRating": {
            "@type": "AggregateRating",
            "ratingValue": "8.7",
            "reviewCount": "123456"
          }
        }
        </script>;
    </head>
    
    <body>
      <! -- Page content -->
      <h1> The movie Star Trek</h1>.
      <p> Directed by Christopher Nolan</p>
      <p> Starring Matthew McConaughey, Anne Hathaway</p>.
      <p> Genre: Sci-Fi, Drama, Adventure</p>
      <p> Release Date: November 7, 2014</p>
      <p> Synopsis:... (detailed description)</p>
    </body>
    
    </html>
    

(5) Accessibility (a11y)

  • Accessibility: ensuring that the website is user-friendly for all users, including those with disabilities, to access and use
  • WCAG Standards: Web Content Accessibility Guidelines
  • Examples:
    1. Text substitution for non-text content
      • As:<img alt="This is a picture" />
    2. keyboard accessible
    3. Clear and consistent navigation
    4. Sufficient color contrast
    5. Subtitles and audio description

-End-