Leaving out the last semicolon of a CSS block

后端 未结 9 657
梦毁少年i
梦毁少年i 2020-11-27 15:43

A couple of questions concerning this:

  • Is it good practice?
  • Will it, on a large scale, result in better load times?
  • Can it result in browsers
9条回答
  •  误落风尘
    2020-11-27 16:22

    Removing declaration stops will not "break" the browsers but should still be left for automated minifiers (especially if you're concerned with loading times - semicolons alone would not add up to much) but should be avoided in the source for maintainability reasons.

    If you are looking for best practices, CSS formatting rules in the Google css styleguide is a very good place to start - not to blindly apply their suggestion but to see their reasoning behind it.

    Use a semicolon after every declaration. End every declaration with a semicolon for consistency and extensibility reasons.

    /* Not recommended */
    .test {
      display: block;
      height: 100px
    }
    /* Recommended */
    .test {
      display: block;
      height: 100px;
    }
    

    Javascript is a different story though - the short answer is always use semicolons, never rely on implicit insertion, but I've never seen an answer better and more thorough than as prescribed by Google in yet another styleguide of theirs:

    There are a couple places where missing semicolons are particularly dangerous:

    // 1.
    MyClass.prototype.myMethod = function() {
      return 42;
    }  // No semicolon here.
    
    (function() {
      // Some initialization code wrapped in a function to create a scope for locals.
    })();
    
    
    
    var x = {
      'i': 1,
      'j': 2
    }  // No semicolon here.
    
    // 2.  Trying to do one thing on Internet Explorer and another on Firefox.
    // I know you'd never write code like this, but throw me a bone.
    [normalVersion, ffVersion][isIE]();
    
    
    
    var THINGS_TO_EAT = [apples, oysters, sprayOnCheese]  // No semicolon here.
    
    // 3. conditional execution a la bash
    -1 == resultOfOperation() || die();
    

    So what happens?

    1. JavaScript error - first the function returning 42 is called with the second function as a parameter, then the number 42 is "called" resulting in an error.
    2. You will most likely get a 'no such property in undefined' error at runtime as it tries to call x[ffVersion][isIE]().
    3. die is called unless resultOfOperation() is NaN and THINGS_TO_EAT gets assigned the result of die().

    Why?

    JavaScript requires statements to end with a semicolon, except when it thinks it can safely infer their existence. In each of these examples, a function declaration or object or array literal is used inside a statement. The closing brackets are not enough to signal the end of the statement. Javascript never ends a statement if the next token is an infix or bracket operator.

    This has really surprised people, so make sure your assignments end with semicolons.

提交回复
热议问题