I have been collecting gold for a long time. Recently, TAKING advantage of the epidemic, I decided to contribute to the community and started writing. Since the work of their own accumulated articles slowly sorted out to share on the nuggets, code words are not easy, if it is helpful, please like and follow the nuggets account and the public number, I will always share my front end development advanced full stack road, we work together.

Today, I will give you the front end performance optimization question which will be asked in the front end interview. I will give you three stages. The first stage will cover the basic code optimization, followed by network transport layer optimization and page loading speed optimization.

Pay attention, don’t get lost.

To read all the articles, click here

Reading time: 3 minutes



Read this article to learn:

  • The overall idea of performance optimization
  • Performance optimization at the HTML, CSS and JavaScript levels

Why do performance tuning

  • Users: Improve user experience and page performance
  • Developer: Reflects the will of the company and the skills of the developers

The overall direction of performance optimization

  • Efficient: Rational allocation of resources
  • Fast: Reduce wait time
  • Standard:
    • First Meaningful Paint (FMP, when the main content is shown on the page)
    • Hero Rendering Times, a new metric for measuring user experience, when the things that the user cares about most are rendered.
    • Time to Interactive (TTI) is when the page layout is stable, key page fonts are visible, and the main process is available to process user input, so basically the user can click on the UI and interact with it.
    • Input Responsiveness (time required for an interface to respond to user Input)
    • Perceptual Speed Index (PSI), or Perceptual Speed Index, measures how quickly a page visually changes during loading; the lower the score, the better)

To optimize the direction

HTML/CSS optimization

  • Don’t use JS if you can solve a problem with HTML/CSS

    • Faster development and lower maintenance costs
    • Applicable scenario
    // Highlight nav li {opacity: 0.5; } nav li:hover { opacity: 1; }Copy the code

    // Mouse hover display module. Menu {display: none; } .nav:hover + .menu { display: inline-block; } .menu:before { content:' ';
        position: absolute;
        top: -20px;
        left: 0px;
        width: 100%;
        height: 20px;
    }Copy the code

    • Custom radio/ Checkbox styles
    input[type=checkbox]{}
    input[type=checkbox]:checked{}Copy the code

    • Use CSS pseudo-classes wisely and use native selectors wisely, such as::focus, @media, input[type=email]:invalid
    • Use sASS, SCSS and other precompilers
  • Optimizing HTML tags

    • The text<p><h1>Reduce CSS code
    • The form<form>
    • The list of<ol><ul>
    • The picture<img><picture>
    • link<a><button>
    • Use the input Type value as appropriate
    • Use HTML5 for semantic tags
    </nav> </nav> <header></header> <main> <section></section> </main> <footer></footer>Copy the code

  • Don’t abuse expensive styles

    • box-shadow,border-radius,floatA lot of computing needs to be done by the browser, so use it less
  • Selector merge

    • Combining a series of selectors with common property content compresses space and resource overhead
  • 0 values go to units

    • For attributes with a value of 0, try not to add units to increase compatibility

JS optimization

  • Reduce front-end code coupling
    • Use pass-throughs to reduce coupling
    • Use policy patterns to extract common components, parameters, and encapsulated requests
  • JS writing optimization

    • Write code in a strongly typed style, specifying variable types and return types
    • Literals and local variables are the fastest to access, array elements and object members are relatively slow
    //bad
    let num,
        str,
        obj;
    //good
    let num = 0;
        str = ' ',
        obj = null;
    
    //bad
    getPrice:function(price){
        if (price < 0) {
            return false;
        }else {
            return price * 10
        }
    }
    //good
    getPrice:function(price){
        if (price < 0) {
            return- 1; }else {
            returnPrice * 10}} // The compiler has compiled the function, the type change causes the function to be rolled back to the general state, and the function is regeneratedCopy the code

    • Reduce scoped lookups
      • Try not to expose your code to global scope as much as possible. The longer a variable is searched from local scope to global scope, the slower it is
    //bad
    <script>
        var map = document.querySelector('#imap');
        map.style.height = '10px';
    </script>
    //good
    <script>
        !function() {
            var map = document.querySelector('#imap');
            map.style.height = '10px';
        }
    </script>Copy the code

    • The deeper the object is nested, the slower the reading
      • Meaningless object nesting slows down the read speed
    • Avoid using ==
      • Use === directly when determining the type
    • Merge expression
      • Use the triadic operator instead of the simple if-else
    //bad
    function getPrice(count){
        if(count < 0){
            return- 1; }else {
            return count * 100;
        }
    }
    //good
    function getPrice(count){
        return count <0 ? return-1 : count * 100; } // When the code is compressed, the immediate writing isif-else, the compression tool will also help you change it to the ternary operatorCopy the code

  • Simplify your code with ES6

    • Use arrow functions instead of small functions
    Var num = [4,6,8,3,1,0]function (a,b){
        return a-b;
    })
    //good
    num.sort(a,b => a-b);Copy the code

    • Use ES6 classes
    class Person {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
        addAge() {
            this.age++;
        }
        setName(name) { this.name = name; }}Copy the code

    • String concatenation
    leturl = `/list.html? page=${page}&type=${type}`;Copy the code

    • Block level scoped variables, using let instead of var

Front-end performance optimization series consists of three parts. Click the profile picture on the home page to continue learning



Please comment if you have any questions. Code word is not easy, point a like to go again!