Frontend Interview Knowledge Collection - Comprehensive

HTML, HTTP, Web Comprehensive Questions

Common sorting algorithm time complexity and space complexity

Sorting algorithm comparison

What SEO should frontend pay attention to

  1. Reasonable title, description, keywords: search engines weight these three in descending order. Title should emphasize key points, with important keywords appearing no more than twice and positioned early. Different pages should have different titles. Description should summarize page content concisely, with appropriate length and no keyword stuffing. Different pages should have different descriptions. Keywords should list important keywords only.
  2. Semantic HTML code compliant with W3C standards: semantic code helps search engines understand web pages easily.
  3. Important content HTML code placed first: search engines crawl HTML from top to bottom. Some search engines have length limits on crawling, so placing important content first ensures it gets crawled.
  4. Don’t output important content with JS: crawlers don’t execute JS to get content.
  5. Minimize iframe usage: search engines don’t crawl content inside iframes.
  6. Non-decorative images must include alt attributes.
  7. Improve website speed: website speed is an important factor in search engine ranking.

Session tracking methods in web development

  1. cookie
  2. session
  3. URL rewriting
  4. Hidden input
  5. IP address

Difference between <img>’s title and alt

  1. title is one of the global attributes, used to provide additional advisory information for elements. It’s usually displayed when the mouse hovers over the element.
  2. alt is a unique attribute of <img>, an equivalent description of the image content. It’s displayed when the image cannot load and is used by screen readers to interpret images. It improves image accessibility. Except for purely decorative images, it must have meaningful values, and search engines focus on analyzing it.

What is doctype? Examples of common doctypes and their characteristics

  1. <!doctype> declaration must be at the top of the HTML document, before the <html> tag. In HTML5, it’s case-insensitive.
  2. <!doctype> is not an HTML tag; it’s an instruction to tell the browser which HTML version the current page uses.
  3. Modern browser HTML layout engines determine whether to use quirks mode or standards mode for rendering by checking the doctype. Some browsers have a “almost standards” mode.
  4. In HTML4.01, <!doctype> points to a DTD. Since HTML4.01 is based on SGML, the DTD specifies markup rules to ensure the browser renders content correctly.
  5. HTML5 is not based on SGML, so DTD is not needed.

Common doctypes:

  1. HTML4.01 Strict: Does not allow presentational or deprecated elements (e.g., font) or framesets. Declaration: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. HTML4.01 Transitional: Allows presentational and deprecated elements (e.g., font), but not framesets. Declaration: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  3. HTML4.01 Frameset: Allows presentational elements, deprecated elements, and framesets. Declaration: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
  4. XHTML1.0 Strict: Does not allow presentational or deprecated elements, or framesets. Document must be well-formed XML. Declaration: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  5. XHTML1.0 Transitional: Allows presentational and deprecated elements, but not framesets. Document must be well-formed XML. Declaration: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  6. XHTML 1.0 Frameset: Allows presentational elements, deprecated elements, and framesets. Document must be well-formed XML. Declaration: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
  7. HTML 5: <!doctype html>

HTML global attributes

References: MDN: html global attribute or W3C HTML global-attributes

  • accesskey: Sets a keyboard shortcut for quick access to an element. E.g., <a href="#" accesskey="a">aaa</a> — in Firefox on Windows, press alt + shift + a to activate the element.
  • class: Sets the class identifier for an element. Multiple class names are separated by spaces. CSS and JavaScript can access elements through the class attribute.
  • contenteditable: Specifies whether the element content is editable.
  • contextmenu: Customizes the right-click menu content.
  • data-*: Adds custom attributes to elements.
  • dir: Sets the text direction of the element.
  • draggable: Sets whether the element is draggable.
  • dropzone: Sets the drag-and-drop type: copy, move, link.
  • hidden: Indicates whether an element is relevant to the document. Stylistically, it hides the element, but this property shouldn’t be used for styling effects.
  • id: Element ID, unique within the document.
  • lang: The language of the element’s content.
  • spellcheck: Whether to enable spell and grammar checking.
  • style: Inline CSS styles.
  • tabindex: Sets whether the element can receive focus and be navigated to via Tab.
  • title: Advisory information related to the element.
  • translate: Whether the element and its descendant node content should be localized.

What is web semantics and what are its benefits

Web semantics means using HTML markup to represent the information contained in a page, including semantic HTML tags and semantic CSS naming. Semantic HTML tags mean using tags with semantic meaning (e.g., h1-h6) to appropriately represent document structure. Semantic CSS naming means adding meaningful class or id to HTML tags to supplement unexpressed semantics, such as Microformat describing information by adding class attributes following rules. Why semantics is needed:

  • Clear page structure even without styles.
  • Better reading experience for blind users using screen readers.
  • Search engines better understand the page, aiding indexing.
  • Facilitates team project sustainability and maintenance.

HTTP methods

  1. For a server to be HTTP1.1 compatible, it only needs to implement GET and HEAD methods for resources.
  2. GET is the most commonly used method, typically for requesting the server to send a resource.
  3. HEAD is similar to GET, but the server only returns headers in the response, not the entity body.
  4. PUT instructs the server to create a new document named by the requested URL using the request body, or if that URL already exists, replace it with this body.
  5. POST was originally used to input data to the server. In practice, it’s commonly used to support HTML forms. Form data is typically sent to the server, which then sends it to its destination.
  6. TRACE initiates a loopback diagnostic at the destination server. The last-stop server bounces back a TRACE response with the original request message it received. TRACE is mainly used for diagnostics, verifying whether requests passed through the request/response chain as intended.
  7. OPTIONS method requests the web server to inform it of the various functions it supports. It can query which methods the server supports or which methods certain special resources support.
  8. DELETE requests the server to delete the resource specified by the request URL.

Steps from entering a URL in the browser address bar to displaying the page (using HTTP as an example)

  1. Enter URL in the browser address bar.
  2. Browser checks the cache. If the requested resource is in the cache and is fresh, skip to the transcoding step.
    1. If the resource is not cached, initiate a new request.
    2. If cached, check if it’s fresh enough. If fresh enough, provide it directly to the client; otherwise, validate with the server.
    3. Freshness is typically controlled by two HTTP headers: Expires and Cache-Control:
      • HTTP1.0 provides Expires, an absolute time indicating the cache freshness date.
      • HTTP1.1 adds Cache-Control: max-age=, with value being the maximum freshness time in seconds.
  3. Browser parses the URL to get the protocol, host, port, and path.
  4. Browser assembles an HTTP (GET) request message.
  5. Browser obtains the host IP address in the following process:
    1. Browser cache
    2. Local cache
    3. Hosts file
    4. Router cache
    5. ISP DNS cache
    6. DNS recursive query (may involve load balancing resulting in different IPs each time)
  6. Open a socket to establish a TCP connection with the target IP address and port, three-way handshake as follows:
    1. Client sends a TCP SYN=1, Seq=X packet to the server port.
    2. Server sends back SYN=1, ACK=X+1, Seq=Y response packet.
    3. Client sends ACK=Y+1, Seq=Z.
  7. After TCP connection is established, send the HTTP request.
  8. Server accepts the request and parses it, forwarding the request to the service program. For example, virtual hosts use the HTTP Host header to determine which service program to handle the request.
  9. Server checks whether the HTTP request headers contain cache validation information. If the cache is validated as fresh, return corresponding status code like 304.
  10. The handler reads the complete request and prepares the HTTP response, possibly requiring database queries and other operations.
  11. Server sends the response message back to the browser through the TCP connection.
  12. Browser receives the HTTP response, then decides to close the TCP connection or keep it alive for reuse. Closing the TCP connection involves a four-way handshake:
    1. Active side sends Fin=1, Ack=Z, Seq=X packet.
    2. Passive side sends ACK=X+1, Seq=Z packet.
    3. Passive side sends Fin=1, ACK=X, Seq=Y packet.
    4. Active side sends ACK=Y, Seq=X packet.
  13. Browser checks the response status code: whether it’s 1XX, 3XX, 4XX, 5XX. These cases are handled differently from 2XX.
  14. If the resource is cacheable, perform caching.
  15. Decode the response (e.g., gzip decompression).
  16. Determine how to handle based on resource type (assuming the resource is an HTML document).
  17. Parse the HTML document, build the DOM tree, download resources, construct the CSSOM tree, execute JS scripts. These operations don’t have a strict sequential order. The following explains each:
  18. Build the DOM tree:
    1. Tokenizing: Parse the character stream into tokens according to HTML specification.
    2. Lexing: Convert tokens into objects and define properties and rules.
    3. DOM construction: Build the DOM tree from objects based on HTML token relationships.
  19. During parsing, when encountering images, stylesheets, JS files, initiate downloads.
  20. Build the CSSOM tree:
    1. Tokenizing: Convert character stream to token stream.
    2. Node: Create nodes based on tokens.
    3. CSSOM: Build the CSSOM tree from nodes.
  21. Build the render tree from the DOM tree and CSSOM tree:
    1. Traverse all visible nodes from the DOM tree’s root. Invisible nodes include: 1) inherently invisible tags like script, meta; 2) nodes hidden by CSS, like display: none.
    2. For each visible node, find the appropriate CSSOM rules and apply them.
    3. Emit the content of visible nodes with their computed styles.
  22. JS parsing as follows:
    1. Browser creates the Document object and parses HTML, adding parsed elements and text nodes to the document. At this point, document.readystate is loading.
    2. When the HTML parser encounters scripts without async and defer, it adds them to the document, then executes inline or external scripts. These scripts execute synchronously, and the parser pauses during script download and execution. This allows document.write() to insert text into the input stream. Sync scripts often simply define functions and register event handlers, and they can traverse and manipulate the script and previous document content.
    3. When the parser encounters a script with the async attribute, it starts downloading the script and continues parsing the document. The script executes as soon as it finishes downloading, but the parser doesn’t stop to wait for it. Async scripts cannot use document.write(), and they can only access their own script and previous document elements.
    4. When the document finishes parsing, document.readState becomes interactive.
    5. All defer scripts execute in the order they appear in the document. Deferred scripts can access the complete document tree and cannot use document.write().
    6. Browser fires the DOMContentLoaded event on the Document object.
    7. At this point, the document is fully parsed. The browser may still be waiting for content like images to load. When these contents finish loading and all async scripts finish loading and executing, document.readState becomes complete, and the window fires the load event.
  23. Display the page (the page gradually displays during HTML parsing).

HTTP access process

What is the structure of an HTTP request message?

As defined in rfc2616:

  1. The first line is the Request-Line including: HTTP method, request URI, protocol version, CRLF.

  2. After the first line are several request headers, including general-header, request-header, or entity-header, each on one line ending with CRLF.

  3. There’s a CRLF separator between the request headers and the message body.

  4. Depending on the actual request, it may include a message body.

    A request message example:

    GET /Protocols/rfc2616/rfc2616-sec5.html HTTP/1.1
    Host: www.w3.org
    Connection: keep-alive
    Cache-Control: max-age=0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
    Referer: https://www.google.com.hk/
    Accept-Encoding: gzip,deflate,sdch
    Accept-Language: zh-CN,zh;q=0.8,en;q=0.6
    Cookie: authorstyle=yes
    If-None-Match: "2cc8-3e3073913b100"
    If-Modified-Since: Wed, 01 Sep 2004 13:24:52 GMT
    
    name=qiu&age=25
    

What is the structure of an HTTP response message?

As defined in rfc2616:

  1. The first line is the status line including: HTTP version, status code, status description, followed by CRLF.

  2. After the first line are several response headers, including: general headers, response headers, entity headers.

  3. There’s a CRLF blank line separating response headers and the response body.

  4. Finally, a possible message body.

    A response message example:

    HTTP/1.1 200 OK
    Date: Tue, 08 Jul 2014 05:28:43 GMT
    Server: Apache/2
    Last-Modified: Wed, 01 Sep 2004 13:24:52 GMT
    ETag: "40d7-3e3073913b100"
    Accept-Ranges: bytes
    Content-Length: 16599
    Cache-Control: max-age=21600
    Expires: Tue, 08 Jul 2014 11:28:43 GMT
    P3P: policyref="http://www.w3.org/2001/05/P3P/p3p.xml"
    Content-Type: text/html; charset=iso-8859-1
    
    {"name": "qiu", "age": 25}
    

How to optimize website performance

Yahoo Best Practices for Speeding Up Your Web Site:

  • Content aspects:

    1. Reduce HTTP requests: combine files, CSS sprites, inline images.
    2. Reduce DNS queries: the browser cannot download any files from a host until DNS queries are complete. Methods: DNS caching, distributing resources across an appropriate number of hostnames to balance parallel downloads and DNS queries.
    3. Avoid redirects: unnecessary intermediate access.
    4. Make Ajax cacheable.
    5. Lazy load non-essential components.
    6. Preload future-needed components.
    7. Reduce the number of DOM elements.
    8. Distribute resources across different domains: browsers have a limited number of concurrent downloads from a single domain; increasing domains can improve parallel download capacity.
    9. Reduce iframe count.
    10. Avoid 404 errors.
  • Server aspects:

    1. Use CDN.
    2. Add Expires or Cache-Control response headers.
    3. Gzip compress components.
    4. Configure ETag.
    5. Flush buffer early.
    6. Use GET for Ajax requests.
    7. Avoid empty src attributes on img tags.
  • Cookie aspects:

    1. Reduce cookie size.
    2. Use cookie-free domains for resources.
  • CSS aspects:

    1. Place stylesheets at the page top.
    2. Avoid CSS expressions.
    3. Use instead of @import.
    4. Avoid IE filters.
  • JavaScript aspects:

    1. Place scripts at the page bottom.
    2. Externalize JavaScript and CSS.
    3. Compress JavaScript and CSS.
    4. Remove unused scripts.
    5. Reduce DOM access.
    6. Design event listeners wisely.
  • Image aspects:

    1. Optimize images: choose appropriate color depth based on actual color needs, compress.
    2. Optimize CSS sprites.
    3. Don’t scale images in HTML.
    4. Ensure favicon.ico is small and cacheable.
  • Mobile aspects:

    1. Keep components under 25k.
    2. Pack components into a multipart document.

What is progressive enhancement

Progressive enhancement emphasizes accessibility, semantic HTML tags, external stylesheets, and scripts in web design. It ensures everyone can access basic page content and functionality while providing better user experience for high-end browsers and high-bandwidth users. The core principles are:

  • All browsers must be able to access basic content.
  • All browsers must be able to use basic functionality.
  • All content is contained in semantic tags.
  • Enhanced layouts are provided through external CSS.
  • Enhanced functionality is provided through non-intrusive, external JavaScript.
  • End-user web browser preferences are respected.

HTTP status codes and their meanings

Reference RFC 2616

  • 1XX: Informational status codes
    • 100 Continue: The client should continue sending the request. This temporary response notifies the client that part of its request has been received by the server and has not been rejected. The client should continue sending the remainder of the request, or if the request is complete, ignore this response. The server must send a final response after the request is complete.
    • 101 Switching Protocols: The server has understood the client’s request and will notify the client through the Upgrade message header to use a different protocol to complete the request. After sending the last blank line of this response, the server will switch to the protocols defined in the Upgrade header.
  • 2XX: Success status codes
    • 200 OK: Request succeeded. The requested response headers or data body will be returned with this response.
    • 201 Created: Request fulfilled, new resource created.
    • 202 Accepted: Request accepted for processing, but processing not yet complete.
    • 203 Non-Authoritative Information: Returned meta-information is not from the original server but from a local or third-party copy.
    • 204 No Content: Server successfully processed the request but no content to return.
    • 205 Reset Content: Server successfully processed the request, asks client to reset document view.
    • 206 Partial Content: Server successfully processed partial GET request.
  • 3XX: Redirection
    • 300 Multiple Choices: Requested resource has multiple representations available.
    • 301 Moved Permanently: Requested resource has been permanently moved to a new URI.
    • 302 Found: Requested resource temporarily moves to a different URI.
    • 303 See Other: Response to the request can be found under a different URI.
    • 304 Not Modified: Resource has not been modified since last request.
    • 305 Use Proxy: Requested resource must be accessed through the specified proxy.
    • 306 (unused): Previously used, now reserved.
    • 307 Temporary Redirect: Requested resource temporarily responds from different URI.
  • 4XX: Client error
    • 400 Bad Request: Request could not be understood by server due to malformed syntax.
    • 401 Unauthorized: Request requires user authentication.
    • 402 Payment Required: Reserved for future use.
    • 403 Forbidden: Server understood request but refuses to fulfill it.
    • 404 Not Found: Server cannot find requested resource.
    • 405 Method Not Allowed: Method specified in request is not allowed for the resource.
    • 406 Not Acceptable: Server cannot produce response matching client’s Accept headers.
    • 407 Proxy Authentication Required: Client must first authenticate with the proxy.
    • 408 Request Timeout: Client did not produce a request within server’s timeout period.
    • 409 Conflict: Request could not be completed due to conflict with current state of resource.
    • 410 Gone: Requested resource is no longer available at the server.
    • 411 Length Required: Content-Length header is not defined, server refuses to accept request without it.
    • 412 Precondition Failed: One or more preconditions given in request header evaluated to false.
    • 413 Request Entity Too Large: Server refuses to process request because entity is larger than server can handle.
    • 414 Request-URI Too Long: Server refuses to service request because URI is longer than server can interpret.
    • 415 Unsupported Media Type: Request entity has media type not supported by server.
    • 416 Requested Range Not Satisfiable: Cannot supply requested portion of file.
    • 417 Expectation Failed: Server cannot meet requirements of Expect request-header field.
  • 5XX: Server error
    • 500 Internal Server Error: Server encountered unexpected condition preventing it from fulfilling request.
    • 501 Not Implemented: Server does not support functionality required to fulfill request.
    • 502 Bad Gateway: Server, acting as gateway or proxy, received invalid response from upstream server.
    • 503 Service Unavailable: Server currently unable to handle request due to temporary overload or maintenance.
    • 504 Gateway Timeout: Server, acting as gateway or proxy, did not receive timely response from upstream server.
    • 505 HTTP Version Not Supported: Server does not support HTTP protocol version used in request.

CSS Section

What are CSS selectors

  1. * Universal selector: Selects all elements, does not participate in priority calculation, compatible with IE6+.
  2. #X ID selector: Selects element with ID value X, compatibility: IE6+.
  3. .X Class selector: Selects elements whose class contains X, compatibility: IE6+.
  4. X Y Descendant selector: Selects elements matching Y selector among descendant nodes of X selector, compatibility: IE6+.
  5. X Element selector: Selects all elements with tag X, compatibility: IE6+.
  6. :link, :visited, :focus, :hover, :active Link states: Selects link elements in specific states, order LoVe HAte, compatibility: IE4+.
  7. X + Y Adjacent sibling selector: Selects elements matching Y among the first sibling after X, compatibility: IE7+.
  8. X > Y Child selector: Selects elements matching Y among X’s child elements, compatibility: IE7+.
  9. X ~ Y General sibling: Selects elements matching Y among all siblings after X, compatibility: IE7+.
  10. [attr]: Selects all elements with the attr attribute, compatibility IE7+.
  11. [attr=value]: Selects elements with attribute value exactly value.
  12. [attr~=value]: Selects elements whose attribute is a whitespace-separated list, with one of the values exactly value.
  13. [attr|=value]: Selects elements with attribute value exactly value or starting with value-.
  14. [attr^=value]: Selects elements with attribute value starting with value.
  15. [attr$=value]: Selects elements with attribute value ending with value.
  16. [attr=value]*: Selects elements with attribute value containing value.
  17. [:checked]: Selects checked radio buttons, checkboxes, or dropdown options, compatibility: IE9+.
  18. X:after, X::after: after pseudo-element, selects the virtual child element (last child of element). In CSS3, :: indicates pseudo-elements. Compatibility: after for IE8+, ::after for IE9+.
  19. :hover: Elements in mouse hover state. Compatibility: a tag IE4+, all elements IE7+.
  20. :not(selector): Selects elements that do not match the selector. Does not participate in priority calculation, compatibility: IE9+.
  21. ::first-letter: Pseudo-element, selects the first letter of the first line of a block element, compatibility IE5.5+.
  22. ::first-line: Pseudo-element, selects the first line of a block element, compatibility IE5.5+.
  23. :nth-child(an + b): Pseudo-class, selects elements that have an + b - 1 siblings before them, where n >= 0, compatibility IE9+.
  24. :nth-last-child(an + b): Pseudo-class, selects elements that have an + b - 1 siblings after them, where n >= 0, compatibility IE9+.
  25. X:nth-of-type(an+b): Pseudo-class, X is selector, resolves to element tag, selects elements that have an + b - 1 same-tag siblings before them. Compatibility IE9+.
  26. X:nth-last-of-type(an+b): Pseudo-class, X is selector, resolves to element tag, selects elements that have an+b-1 same tag siblings after them. Compatibility IE9+.
  27. X:first-child: Pseudo-class, selects elements matching X that are the first child of their parent. Compatibility IE7+.
  28. X:last-child: Pseudo-class, selects elements matching X that are the last child of their parent. Compatibility IE9+.
  29. X:only-child: Pseudo-class, selects elements matching X that are the only child of their parent. Compatibility IE9+.
  30. X:only-of-type: Pseudo-class, selects elements matching X, resolves to element tag, selects if it’s the only element of its type among siblings. Compatibility IE9+.
  31. X:first-of-type: Pseudo-class, selects elements matching X, resolves to element tag, selects if it’s the first element of this type among siblings. Compatibility IE9+.

What is CSS sprite? Advantages and disadvantages?

Concept: Combine multiple small images into one image. Use background-position and element size to adjust which background pattern is displayed.

Advantages:

  1. Reduces HTTP requests, greatly improving page loading speed.
  2. Increases image information redundancy, improving compression ratio, reducing image size.
  3. Convenient style changes: only need to modify colors or styles on one or a few images.

Disadvantages:

  1. Image merging is cumbersome.
  2. Maintenance is difficult: modifying one image may require re-laying out the entire image and styles.

Difference between display: none; and visibility: hidden;

Commonality: Both make elements invisible.

Differences:

  1. display: none; completely removes the element from the render tree, not occupying any space during rendering. visibility: hidden; does not remove the element from the render tree; the element continues to occupy space during rendering but is invisible.
  2. display: none; is a non-inherited property. Descendant nodes disappear because the element is removed from the render tree; modifying descendant node properties cannot make them visible. visibility: hidden; is an inherited property. Descendant nodes disappear because they inherit hidden; setting visibility: visible can make them visible.
  3. Modifying display of an element in normal flow usually causes document reflow. Modifying the visibility property only causes repaint of that element.
  4. Screen readers do not read display: none; elements but do read visibility: hidden; elements.

CSS hack principles and common hacks

Principle: Use different browsers’ varying support and parsing results for CSS to write styles for specific browsers. Common hacks include 1) property hacks, 2) selector hacks, 3) IE conditional comments.

  • IE conditional comments: Applicable to [IE5, IE9], common format:
<!--[if IE 6]>
Special instructions for IE 6 here
<![endif]-->
  • Selector hacks: Different browsers have different selector support.
/***** Selector Hacks ******/

/* IE6 and below */
* html #uno {
  color: red;
}

/* IE7 */
*:first-child + html #dos {
  color: red;
}

/* IE7, FF, Saf, Opera  */
html > body #tres {
  color: red;
}

/* IE8, FF, Saf, Opera (Everything but IE 6,7) */
html>/**/body #cuatro {
  color: red;
}

/* Opera 9.27 and below, safari 2 */
html:first-child #cinco {
  color: red;
}

/* Safari 2-3 */
html[xmlns*=''] body:last-child #seis {
  color: red;
}

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:nth-of-type(1) #siete {
  color: red;
}

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:first-of-type #ocho {
  color: red;
}

/* saf3+, chrome1+ */
@media screen and (-webkit-min-device-pixel-ratio: 0) {
  #diez {
    color: red;
  }
}

/* iPhone / mobile webkit */
@media screen and (max-device-width: 480px) {
  #veintiseis {
    color: red;
  }
}

/* Safari 2 - 3.1 */
html[xmlns*='']:root #trece {
  color: red;
}

/* Safari 2 - 3.1, Opera 9.25 */
*|html[xmlns*=''] #catorce {
  color: red;
}

/* Everything but IE6-8 */
:root * > #quince {
  color: red;
}

/* IE7 */
* + html #dieciocho {
  color: red;
}

/* Firefox only. 1+ */
#veinticuatro,
x:-moz-any-link {
  color: red;
}

/* Firefox 3.0+ */
#veinticinco,
x:-moz-any-link,
x:default {
  color: red;
}
  • Property hacks: Different browser parsing bugs or methods.
/* IE6 */
#once { _color: blue }

/* IE6, IE7 */
#doce { *color: blue; /* or #color: blue */ }

/* Everything but IE6 */
#diecisiete { color/**/: blue }

/* IE6, IE7, IE8 */
#diecinueve { color: blue\9; }

/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }

/* IE6, IE7 -- acts as an !important */
#veintesiete { color: blue !ie; } /* string after ! can be anything */

Specified value, computed value, used value calculation

  • Specified value: calculated as follows:

    1. If a value is set in the stylesheet, use that value.
    2. If not set and the property is inherited, inherit from the parent element.
    3. If not set and not inherited, use the initial value specified by the CSS specification.
  • Computed value: Calculated from the specified value according to specification-defined behavior, typically converting relative values to absolute values, e.g., em calculated based on font-size. Some properties that use percentages and require layout to determine final values, like width, margin, keep percentages as computed value. Unitless values for line-height also remain as computed value. These values get absolute values when calculating used value. The main purpose of computed value is for inheritance.

  • Used value: The final value after property calculation. For most properties, it can be obtained via window.getComputedStyle. Size values are in pixels. The following properties depend on layout:

    • background-position
    • bottom, left, right, top
    • height, width
    • margin-bottom, margin-left, margin-right, margin-top
    • min-height, min-width
    • padding-bottom, padding-left, padding-right, padding-top
    • text-indent
  1. link is an HTML method, @import is a CSS method.
  2. link supports maximum parallel downloading, @import with excessive nesting leads to serial downloading, causing FOUC.
  3. link can specify alternative stylesheets via rel="alternate stylesheet".
  4. Browser support for link predates @import. @import can hide styles from older browsers.
  5. @import must precede style rules and can reference other files within CSS.
  6. Overall: link is better than @import.

Difference between display: block; and display: inline;

block element characteristics:

  1. In normal flow, if width is not set, it automatically fills the parent container.
  2. margin/padding can be applied.
  3. If no height is set, it expands height to contain child elements in normal flow.
  4. In normal flow layout, it occupies space between preceding and following elements (occupies horizontal space exclusively).
  5. vertical-align is ignored.

inline element characteristics:

  1. Horizontally laid out according to direction.
  2. No line breaks before or after the element.
  3. Controlled by white-space.
  4. margin/padding is ineffective vertically but effective horizontally.
  5. width/height properties are ineffective on non-replaced inline elements; width is determined by content.
  6. For non-replaced inline elements, line box height is determined by line-height. For replaced inline elements, line box height is determined by height, margin, padding, border.
  7. When floated or absolutely positioned, they convert to block.
  8. vertical-align property takes effect.

Differences between PNG, GIF, JPG and how to choose

Reference: Choosing the correct image format

GIF:

  1. 8-bit pixels, 256 colors.
  2. Lossless compression.
  3. Supports simple animation.
  4. Supports boolean transparency.
  5. Suitable for simple animations.

JPEG:

  1. Limited to 256 colors.
  2. Lossy compression.
  3. Controllable compression quality.
  4. No transparency support.
  5. Suitable for photos.

PNG:

  1. Has PNG8 and truecolor PNG.
  2. PNG8 is similar to GIF with 256 color limit, small file size, supports alpha transparency, no animation.
  3. Suitable for icons, backgrounds, buttons.

Which CSS properties are inherited

Common IE6 browser bugs, defects, or inconsistencies with standards, and solutions

  • IE6 does not support min-height. Solution: use CSS hack:
.target {
    min-height: 100px;
    height: auto !important;
    height: 100px;   // In IE6, content height automatically expands beyond this
}
  • ol li item numbers all show as 1, not incrementing. Solution: set display: list-item; on li.

  • Unpositioned parent element with overflow: auto; containing position: relative; child, child overflows when taller than parent. Solution: 1) remove position: relative; from child; 2) if child must be positioned, set parent to position: relative;.

  • IE6 only supports :hover pseudo-class on a tags. Solution: use JS to listen for mouseenter/mouseleave events and add class.

  • IE5-8 does not support opacity. Solution:

.opacity {
    opacity: 0.4;
    filter: alpha(opacity=60); /* for IE5-7 */
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=60)"; /* for IE 8 */
}
  • IE6 treats height smaller than font-size as font-size. Solution: font-size: 0;.
  • IE6 does not support PNG transparent background. Solution: use GIF images in IE6.
  • IE6-7 does not support display: inline-block. Solution: set inline and trigger hasLayout.
    display: inline-block;
    *display: inline;
    *zoom: 1;
  • IE6 doubles margin on floated elements touching parent boundary in the float direction. Solution: 1) use padding to control spacing. 2) set floated element to display: inline; (CSS standard specifies that floated elements with display: inline automatically adjust to block).
  • Setting width and auto horizontal margin on block-level elements doesn’t center them in IE6. Solution: set text-align: center; on the parent element.

How to clear (contain) floats when a container contains multiple floated elements

  1. Add an extra element before the closing tag of the container and set clear: both.
  2. Trigger block formatting context on the parent element (see block-level visual formatting context section).
  3. Use pseudo-elements on the container for clearing. Recommended clearfix method.

What is FOUC? How to avoid it?

Flash of Unstyled Content: The browser displays the document with default styles before the user-defined stylesheet loads, then re-displays the document after user styles load, causing a flash. Solution: Place stylesheets in the document’s head.

How to create a block formatting context (BFC) and what is it used for?

Creating rules:

  1. Root element.
  2. Floating elements (float not none).
  3. Absolutely positioned elements (position set to absolute or fixed).
  4. Elements with display set to inline-block, table-cell, table-caption, flex, or inline-flex.
  5. Elements with overflow not set to visible.

Uses:

  1. Can contain floating elements.
  2. Not covered by floating elements.
  3. Prevents parent-child margin collapsing.

Relationship between display, float, and position

  1. If display is none, position and float are irrelevant; the element generates no box.
  2. Otherwise, if position is absolute or fixed, the box is absolutely positioned, float computes to none, and display adjusts according to the table below.
  3. Otherwise, if float is not none, the box is floated, and display adjusts according to the table below.
  4. Otherwise, if the element is the root element, display adjusts according to the table below.
  5. Otherwise, display remains as specified.

In summary: Absolutely positioned, floated, and root elements all need display adjustment.

Margin collapsing

Two or more adjacent margin values merge into one margin, called margin collapsing. Rules:

  1. Two or more adjacent block elements in normal flow have their vertical margins collapse.
  2. Floating/inline-block/absolutely positioned elements’ margins do not collapse with other elements’ vertical margins.
  3. Elements that create a block formatting context do not have their margins collapse with child elements.
  4. An element’s own margin-bottom and margin-top can also collapse when adjacent.

How to determine an element’s containing block

  1. The root element’s containing block is called the initial containing block. In continuous media, its size equals the viewport and is anchored at the canvas origin. For paged media, its size equals the page area. The initial containing block’s direction property is the same as the root element.
  2. Elements with position as relative or static have their containing block formed by the content box of the nearest block-level (display as block, list-item, table) ancestor.
  3. If the element’s position is fixed, for continuous media, its containing block is the viewport; for paged media, it’s the page area.
  4. If the element’s position is absolute, its containing block is formed by the nearest ancestor with position set to relative, absolute, or fixed, with the following rules:
    • If the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and last inline boxes generated for that element.
    • Otherwise, the containing block is formed by the ancestor’s padding edge.

If no positioned ancestor is found, the containing block is the initial containing block.

Stacking context and layout rules

Default stacking order on the z-axis (bottom to top):

  1. Root element’s border and background.
  2. Elements in normal flow in HTML order.
  3. Floated blocks.
  4. Positioned elements in HTML order.

How to create a stacking context:

  1. Root element.
  2. Positioned elements with z-index not auto.
  3. Flex items with z-index other than ‘auto’.
  4. Elements with opacity less than 1.
  5. In mobile WebKit and Chrome22+, elements with z-index auto and position: fixed also create new stacking contexts.

How to horizontally center an element

  • If the element to be centered is an inline element in normal flow, set text-align: center; on the parent element.

  • If the element to be centered is a block element in normal flow, 1) set a width for the element, 2) set left and right margin to auto. 3) In IE6, you also need to set text-align: center; on the parent element and restore the needed value on the child.

  • If the element to be centered is a floated element, 1) set a width, 2) set position: relative;, 3) set the float direction offset (left or right) to 50%, 4) set the margin in the float direction to negative half of the element width.

  • If the element to be centered is an absolutely positioned element, 1) set a width, 2) set offset to 50%, 3) set the outer margin in the offset direction to negative half of the element width.

  • If the element to be centered is an absolutely positioned element, 1) set a width, 2) set left and right offset to 0, 3) set left and right margins to auto.

How to vertically center an element

Reference: 6 Methods For Vertical Centering With CSS, 8 CSS Methods for Vertical Centering

  • If the element to be centered is single-line text, set line-height greater than font-size on the containing text element.

JavaScript Concepts

Difference and relationship between e.getAttribute(propName) and e.propName on DOM element e

  • e.getAttribute() is a standard DOM method for accessing element attributes, universally applicable across documents. It returns the attribute as set in the source file.
  • e.propName typically accesses specific properties of elements in HTML documents. After the browser parses an element, it generates a corresponding object (e.g., an a tag generates HTMLAnchorElement). These objects’ properties are formed by combining attribute settings according to specific rules. For properties without corresponding DOM properties, only getAttribute can be used.
  • e.getAttribute() returns the value set in the source file, with type string or null (some implementations return “”).
  • e.propName may return string, boolean, object, undefined, etc.
  • Most attributes and properties have a one-to-one correspondence; modifying one affects the other, such as id, title.
  • Some boolean attributes like <input hidden/> need hasAttribute and removeAttribute for detection and setting, or setting the corresponding property.
  • For attributes like href in <a href="../index.html">link</a>, converting to property requires transformation to get the full URL.
  • Some attributes and properties are not one-to-one, e.g., <input value="hello"/> in form controls corresponds to defaultValue. Modifying or setting the value property changes the control’s current value. setAttribute modifying the value attribute does not change the value property.

Differences between offsetWidth/offsetHeight, clientWidth/clientHeight, and scrollWidth/scrollHeight

  • offsetWidth/offsetHeight returns content + padding + border, same effect as e.getBoundingClientRect().
  • clientWidth/clientHeight only returns content + padding, and does not include scrollbar if present.
  • scrollWidth/scrollHeight returns content + padding + overflow content size.

Common XMLHttpRequest properties and methods

  1. readyState: Integer indicating request state, values:
    • UNSENT (0): Object created.
    • OPENED (1): open() successfully called. In this state, request headers can be set, or send() called.
    • HEADERS_RECEIVED (2): All redirects automatically completed, final response HTTP headers received.
    • LOADING (3): Response body being received.
    • DONE (4): Data transfer complete or error occurred.
  2. onreadystatechange: Function called when readyState changes.
  3. status: HTTP status code returned by server (e.g., 200, 404).
  4. statusText: HTTP status text returned by server (e.g., OK, No Content).
  5. responseText: Complete server response as string.
  6. responseXML: Document object, server response parsed as XML document.
  7. abort(): Cancel async HTTP request.
  8. getAllResponseHeaders(): Returns string containing all HTTP headers sent by server in response. Each header is a name/value pair separated by colon, header lines separated by carriage return/line feed.
  9. getResponseHeader(headerName): Returns header value for headerName.
  10. open(method, url, asynchronous [, user, password]): Initializes request to be sent to server. method is HTTP method, case-insensitive; url is relative or absolute URL; asynchronous indicates whether request is async; user and password provide authentication.
  11. setRequestHeader(name, value): Sets HTTP header.
  12. send(body): Initializes request to server. body contains request body, for POST requests it’s key-value pair string; for GET requests, it’s null.

Difference and relationship between focus/blur and focusin/focusout

  1. focus/blur do not bubble; focusin/focusout bubble.
  2. focus/blur have good compatibility. focusin/focusout have good compatibility in browsers except Firefox. For event delegation, consider using event capture in Firefox: elem.addEventListener('focus', handler, true).
  3. Elements that can receive focus:
    1. window.
    2. Links clicked or navigated via keyboard.
    3. Form controls clicked or navigated via keyboard.
    4. Elements with tabindex attribute clicked or navigated via keyboard.

Difference and relationship between mouseover/mouseout and mouseenter/mouseleave

  1. mouseover/mouseout are standard events, supported by all browsers. mouseenter/mouseleave are IE5.5-specific events later adopted by DOM3 standard; modern standard browsers also support them.
  2. mouseover/mouseout are bubbling events. mouseenter/mouseleave do not bubble. When you need to listen for mouse enter/leave events for multiple elements, it’s recommended to delegate mouseover/mouseout for better performance.
  3. In the standard event model, event.target indicates the element entered/left. event.relatedTarget corresponds to the element left/entered. In older IE, event.srcElement indicates the element entered/left. event.toElement indicates the target element being left for. event.fromElement indicates the source element being entered from.
  1. All are saved on the browser side with size limits and same-origin restrictions.
  2. Cookies are sent to the server with requests as session identifiers; the server can modify cookies. Web storage is not sent to the server.
  3. Cookies have a path concept. Sub-paths can access parent path cookies, but parent paths cannot access sub-path cookies.
  4. Validity: Cookies are valid within their set validity period, defaulting to browser closure. sessionStorage is valid until window closure. localStorage is valid long-term until user deletes it.
  5. Sharing: sessionStorage cannot be shared. localStorage is shared across same-origin documents. Cookies are shared across same-origin documents that meet path rules.
  6. Modifications to localStorage trigger update events in other document windows.
  7. Cookies have a secure attribute requiring HTTPS transmission.
  8. Browsers cannot save more than 300 cookies, no more than 20 per server, each cookie no more than 4k. Web storage can support up to 5M.

JavaScript cross-origin communication

Same origin: Two documents have the same origin if they satisfy:

  1. Same protocol.
  2. Same domain.
  3. Same port.

Cross-origin communication: When performing DOM operations or communication in JS, if the target and current window don’t meet same-origin conditions, browsers block cross-origin operations for security. Common cross-origin communication methods:

  • For simple one-way communication like logging, create <img>, <script>, <link>, <iframe> elements and set src, href attributes to target URL for cross-origin requests.
  • For requesting JSON data, use <script> for JSONP requests.
  • For multi-window communication in modern browsers, use HTML5 specification: targetWindow.postMessage(data, origin); where data is the object to send, origin is the target window’s origin. window.addEventListener('message', handler, false); where event.data is the data sent by postMessage, event.origin is the sending window’s origin, event.source is the reference to the sending window.
  • Internal server proxies the cross-origin URL request and returns data.
  • For cross-origin data requests, modern browsers can use HTML5’s CORS functionality. Just have the target server return HTTP header Access-Control-Allow-Origin: * to access cross-origin resources like normal ajax.

How many data types does JavaScript have?

Six basic data types:

  • undefined
  • null
  • string
  • boolean
  • number
  • symbol (ES6)

One reference type:

  • Object

What is a closure, and what is it used for?

A closure is a function defined within a certain scope that can access all variables within that scope. The closure scope chain typically consists of three parts:

  1. The function’s own scope.
  2. The scope where the closure was defined.
  3. The global scope.

Common uses of closures:

  1. Creating privileged methods for access control.
  2. Event handlers and callbacks.

How many ways are there to define functions in JavaScript?

  1. Function declaration
  2. Function operator
  3. Function constructor
  4. ES6 arrow functions

Important reference: MDN: Functions_and_function_scope

Application storage and offline web applications

HTML5 adds application cache, allowing web applications to save themselves in the user’s browser for offline access.

  1. Set the manifest attribute on the html element: <html manifest="myapp.appcache">. The extension is just a convention; the actual recognition is through MIME type text/cache-manifest. So server configuration must ensure correct settings.
  2. The first line of the manifest file is CACHE MANIFEST. The rest are URLs to be cached, one per line. Relative paths are relative to the manifest file’s URL. Comments start with #.
  3. URLs are divided into three types: CACHE: default type. NETWORK: resources never cached. FALLBACK: each line contains two URLs. The second URL is the resource to load and store in cache. The first URL is a prefix. Any URL matching that prefix won’t be cached. If loading such a URL from the network fails, the cached resource specified by the second URL is used instead. Example:

Client-side storage: localStorage and sessionStorage

  • localStorage is valid permanently; sessionStorage is valid until the top-level window is closed.
  • Same-origin documents can read and modify localStorage data. sessionStorage is only accessible by documents in the same window; for example, same-origin documents introduced via iframe.

Article Link:

/en/archive/interview-comprehensive/

# Related Articles