Summary of classic HTML front-end interview questions

Summary of classic HTML front-end interview questions

1. 1 Briefly describe your understanding of HTML semantics? .

  1. Do the right thing with the right label.
  2. HTML semantics make the content of the page structured and clearer, which is convenient for browsers and search engines to parse; it is displayed in a document format even if there is no style>style CSS, and it is easy to read;
  3. Search engine crawlers also rely on HTML tags to determine the context and the weight of each keyword, which is good for SEO;
  4. Make it easier for people who read the source code to divide the website into blocks, which is easy to read, maintain and understand.

1.2 What is the difference between title and alt attributes on tags?

alt is for the search engine to identify, and the alternative text when the image cannot be displayed;
title is the annotation information about the element, mainly for users to interpret.
When the mouse is placed on the text or picture, the title text will be displayed. (Because IE is not standard) In the IE browser, alt plays the role of title and becomes a text prompt.
When defining the img object, write all the alt and title attributes to ensure that it can be used normally in various browsers.

alt is for the search engine to identify, and the alternative text when the image cannot be displayed;
title is the annotation information about the element, mainly for users to interpret.
When the mouse is placed on the text or picture, the title text will be displayed. (Because IE is not standard) In the IE browser, alt plays the role of title and becomes a text prompt.
When defining the img object, write all the alt and title attributes to ensure that it can be used normally in various browsers.

1.3 What are the advantages and disadvantages of iframe?

advantage:

  • Addresses loading issues with slow-loading third-party content such as icons and ads
  • Security sandbox
  • Load scripts in parallel

shortcoming:

  • iframe will block the Onload event of the main page
  • Even if the content is empty, it will take time to load
  • no semantics

1.4 href and src?

  • href (Hypertext Reference) specifies the location of a web resource, thereby defining a link or relationship between the current element or current document and the desired anchor or resource defined by the current attribute. (The purpose is not to reference resources, but to establish a link so that the current label can link to the target address.)
  • src source (abbreviation), points to the location of the external resource, and the content pointed to will be applied to the location of the current tag in the document.
  • The difference between href and src
    • 1. The types of requested resources are different: href points to the location of the network resource, and establishes a connection with the current element (anchor) or the current document (link). When the src resource is requested, the resources it points to will be downloaded and applied to the document, such as JavaScript scripts and img images;
    • 2. The results are different: href is used to establish a connection between the current document and the reference resource; src is used to replace the current content;
    • 3. Browser parsing methods are different: when the browser parses to src, it will suspend the download and processing of other resources until the resource is loaded, compiled, and executed. The same is true for pictures and frames, similar to applying the pointed resource to current content. This is why it is recommended to put the js script at the bottom instead of the head.

1.5 What is the difference between HTML, XHTML, and XML

  • HTML (Hypertext Markup Language): Before html4.0, HTML had implementation and then standards, resulting in very confusing and loose HTML
  • XML (Extensible Markup Language): It is mainly used to store data and structures, and is extensible. The familiar JSON also has a similar role, but it is more lightweight and efficient, so the XML market is getting smaller and smaller now
  • XHTML (Extensible Hypertext Markup Language): Based on the above two, W3C was born to solve the problem of HTML confusion, and based on this, HTML5 was born. The practice of adding it at the beginning came from this. If it is not added, it is compatible with confusing HTML <!DOCTYPE html>. Added is the standard mode.

1.6 What is the function of srcset of img?

Responsive images can be designed, and we can use two new attributes srcset and sizes to provide more additional resource images and hints to help the browser choose the correct resource.

srcset defines the set of images we allow the browser to choose from, and the size of each image.

sizes defines a set of media conditions (such as screen width) and indicates what image size is the best choice when certain media conditions are true.

So, with these attributes, the browser will:

  • View device width
  • Check which media condition is first true in the sizes list
  • View the slot size given to this media query
  • Loads the image referenced in the srcset list closest to the selected slot size

srcset provides the ability to select pictures according to screen conditions

Clock

1.7 What is the difference between link and @import?

  • link belongs to XHTML tags, while @import is provided by CSS.
  • When the page is loaded, the link will be loaded at the same time, and the CSS referenced by @import will wait until the page is loaded before loading.
  • import can only be recognized by IE 5 and above, and link is an XHTML tag, so there is no compatibility problem.
  • The style weight of the link method is higher than that of @import.
  • The difference when using dom to control styles. When using javascript to control the dom to change the style, you can only use the link tag, because @import is not controlled by the dom.

1.8 What is your understanding of BFC?

Written explanation: BFC (Block Formatting Context) dismantling in English

  • Block: Block here can be understood as Block-level Box, which refers to the standard of block-level boxes
  • Formatting context: block-level context formatting, which is a rendering area in the page, and has a set of rendering rules, which determine how its child elements will be positioned, as well as the relationship and interaction with other elements

BFC refers to an independent rendering area, only Block-level Box participates, it specifies how the internal Block-level Box is laid out, and has nothing to do with the outside of this area .

Its function is to isolate the elements inside the BFC from the outside elements in an independent area .

How to form?

BFC trigger conditions:

  • The root element, the HTML element
  • position: fixed/absolute
  • float is not none
  • overflow is not visible
  • The value of display is inline-block, table-cell, table-caption
  • What is the role?
    • Prevent margins from overlapping
    • Two-column layout, preventing text wrapping, etc.
    • Prevent elements from collapsing

1.9 What are the new features of html5, and which elements have been removed? How to deal with the browser modesty problem of HTML5 new tab? How to distinguish HTML and HTML5?

* HTML5 is no longer a subset of SGML, mainly about the addition of image, location, storage, multitasking and other functions.

* Painting canvas

video and audio elements for media playback

Local offline storage localStorage stores data for a long time, and the data will not be lost after the browser is closed;

The sessionStorage data is automatically deleted after the browser is closed

Content elements with better semantics, such as article, footer, header, nav, section

Form controls, calendar, date, time, email, url, search

New technology webworker, websockt, Geolocation

* element removed

Elements of pure expression: basefont, big, center, font, s, strike, tt, u;

Elements that negatively affect usability: frame, frameset, noframes;

Support HTML5 new tags:

* IE8/IE7/IE6 supports tags generated by the document.createElement method,

You can use this feature to make these browsers support HTML5 new tags,

After the browser supports the new tab, you also need to add the default style of the tab:

* Of course, the best way is to use a mature framework directly, the most used one is the html5shim framework

1.10 What are the kernels of browsers? What are the tolerances of browsers that are often encountered? What is the reason, what is the solution, and what are the common hacks?

* Trident kernel of IE browser, Gecko of Mozilla, WebKit of Google, Presto kernel of Opera;

* The image of png24 appears in the background on the iE6 browser, the solution is to make it PNG8.

* Browser default margin and padding are different. The solution is to add a global *{margin:0;padding:0;} to unify.

* IE6 bilateral margin bug: after the block attribute label float, there is a horizontal margin, and the margin displayed in ie6 is larger than the setting.

The double distance generated by floating ie #box{ float:left; width:10px; margin:0 0 0 100px;}

In this case, IE will generate a distance of 20px. The solution is to add --_display:inline; to the float label style control to convert it into an inline attribute. (_This symbol is only recognized by ie6)

The method of progressive recognition gradually excludes the part from the whole.

First, cleverly use the "\9" mark to separate the IE browser from all cases.

Then, use "+" again to separate IE8 from IE7 and IE6, so that IE8 has been recognized independently.

css

​ .bb{

​ background-color:#f1ee18;/ All recognition /

​ .background-color:#00deff\9; / IE6, 7, 8 recognition /

​ +background-color:#a200ff;/ IE6, 7 recognition /

_background-color:#1e0bd1;/ IE6 recognition /

​ }

* Under IE, you can use the method of obtaining regular attributes to obtain custom attributes,

​ You can also use getAttribute() to get custom attributes;

​ Under Firefox, you can only use getAttribute() to get custom attributes.

​ Solution: Uniformly obtain custom attributes through getAttribute().

* Under IE, the even object has x, y attributes, but no pageX, pageY attributes;

Under Firefox, the event object has pageX, pageY attributes, but no x, y attributes.

* (Conditional comment) The disadvantage is that it may increase the number of additional HTTP requests under IE browser.

* By default, the Chrome Chinese interface will force texts smaller than 12px to be displayed at 12px, which can be solved by adding the CSS property -webkit-text-size-adjust: none;

After the hyperlink is visited, the hover style will not appear. The clicked and visited hyperlink style will no longer have hover and active. The solution is to change the order of the CSS properties:

L-V-H-A : a:link {} a:visited {} a:hover {} a:active {}

1.11 common compatibility issues with html?

1. The use of display caused by the double-sided distance BUG float

2.3 Pixel problem caused by using float using dislpay:inline -3px

3. The hyperlink hover becomes invalid after clicking. Use the correct writing order link visited hover active

4. IE z-index problem to add position: relative to the parent

5. Png transparently uses js code to change

6.Min-height Minimum height! Important to resolve'

7. Select is covered under ie6 using iframe nesting

8. Why is there no way to define a container with a width of about 1px (caused by the default line height of IE6, use over: hidden, zoom: 0.08 line-height: 1px)

9. 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*/

}

\10. IE6 does not support PNG transparent background, solution: use gif image under IE6

1.12 What is margin overlap? What is the result of the overlap?

Margin overlap is margin-collapse.

In CSS, the margins of two adjacent boxes (which may be siblings or ancestors) can be combined into a single margin. This way of combining margins is called collapsing, and the combined margins are thus called collapsing margins.

Folding results follow the following calculation rules:

When two adjacent margins are both positive, the collapsed result is the larger value between them.

When two adjacent margins are both negative, the folding result is the larger value of the two absolute values.

When the two margins are positive and negative, the folding result is the sum of the two.

1.13 Can you describe the difference between progressive enhancement and graceful degradation?

Progressive enhancement: Build pages for low-version browsers to ensure the most basic functions, and then improve and add functions such as effects and interactions for advanced browsers to achieve a better user experience.

Graceful degradation: build complete functionality from the beginning, and then make it compatible with lower version browsers.

Difference: Graceful degradation starts with the complex status quo and tries to reduce the provisioning of the user experience, while progressive enhancement starts with a very basic, working version and expands to meet the needs of future environments. Degradation (decay of functionality) means looking backward; progressive enhancement means looking forward while keeping its roots in a safe place.

"Graceful degradation" view

The "graceful degradation" point of view believes that websites should be designed for the most advanced and complete browsers. And arrange the testing work under browsers that are considered "outdated" or lacking functions in the last stage of the development cycle, and limit the testing object to the previous version of mainstream browsers (such as IE, Mozilla, etc.).

Under this design paradigm, older browsers are considered to provide only a "poor, but passable" browsing experience. You can make some minor adjustments to suit a particular browser. But since they are not the focus of our attention, other than fixing larger bugs, other differences will be simply ignored.

"Progressive Enhancement" Viewpoint

The "progressive enhancement" view argues that the focus should be on the content itself.

Content is what motivates us to build a website. Some sites display it, others collect it, some seek it out, some manipulate it, and some sites even include all of the above, but the same thing is that they all involve content. This makes "progressive enhancement" a much more reasonable design paradigm. That's why it was immediately adopted by Yahoo! and used to build out its "Graded Browser Support" strategy.

1.14 New tags for HTML5 and CSS3

HTML5: nav, footer, header, section, hgroup, video, time, canvas, audio…CSS3: RGBA, opacity, text-shadow, box-shadow, border-radius, border-image, border-color, transform…;

1.15 What is the role of DOCTYPE? What is the difference between strict mode and promiscuous mode?

! DOCTYPE tells the browser to parse the page according to the HTML5 standard, if not written, it will enter the promiscuous mode
Strict mode (standard mode): parse the code according to the w3c standard Promiscuous
mode (weird mode): the browser parses the code in its own way, promiscuous mode usually simulates the old Browser behavior to prevent old sites from working
HTML5 has no DTD, so there is no difference between strict mode and mixed mode. HTML5 has a relatively loose method. When implementing, it has achieved backward compatibility as much as possible (HTML5 has no strict and promiscuous).

1.16 Tell me about the offline storage of HTML5?

Offline storage of HTML5 is a web application caching technology. By saving the resources of web applications (such as HTML files, CSS style sheets, JavaScript codes and images, etc.) able to work. Offline storage can improve the performance and accessibility of web applications and provide a more stable and reliable way to serve web applications.

In HTML5, the Application Cache API is used to implement offline storage. By adding a manifest attribute to the head of the HTML file to point to a manifest file describing the list of resources that need to be cached, offline storage can be enabled. Once a web application is cached offline, users can access the application without a network connection without downloading resources from remote servers.

Although offline storage can improve the performance and accessibility of web applications, developers should be aware of its drawbacks. Since the data stored offline is kept on the local computer, if the data is tampered with or corrupted, the web application may be compromised or not function properly. In addition, data stored offline may also take up large amounts of local storage space, which may affect the user's device performance.

1.17 Tell me how to do a good job in SEO?

  1. Website structure optimization: Ensure that the website structure is clear and concise, and avoid using excessive Flash, JavaScript and other technologies that are unfriendly to search engines.
  2. Keyword optimization: keywords should be determined according to factors such as the industry to which the website belongs, target users, etc., and should be reasonably used in titles, texts, pictures, etc., but at the same time, avoid excessive use of keywords to avoid being recognized by search engines for spam.
  3. 内容优化:要提供高质量、有价值的内容,吸引用户留下来,增加用户停留时间和页面访问量,同时也可以提升网站的信誉度和排名。
  4. 外部链接优化:要通过寻找相关的高质量外部链接,来提高网站的权重和排名。

1.18 说一下drag api?

Drag API是一种Web API,可以将拖放功能添加到网页中。它允许用户通过点击和拖动鼠标,将某些元素从一个位置移动到另一个位置。

使用Drag API,开发者可以在网页上实现自定义拖放功能,并对其进行细粒度的控制。例如,可以定义哪些元素可以被拖动,哪些元素可以作为拖放目标,以及如何处理拖放事件等。

Drag API提供了几个主要的接口和事件:

  1. Draggable:通过将draggable属性设置为true,将一个元素标记为可拖动的。
  2. Dragstart事件:当用户开始拖动一个元素时触发。
  3. Dragenter事件:当一个可拖动元素进入一个可以放置的元素区域时触发。
  4. Dragover事件:当一个可拖动元素在一个可以放置的元素区域内移动时触发。
  5. Drop事件:当用户松开鼠标,释放一个可拖动元素并将其放置到一个可以放置的元素区域时触发。
  6. Dragend事件:当用户完成拖动操作后触发。

通过使用Drag API,开发者可以创建各种有趣和交互性强的网页应用程序,例如拖动图片上传、拖动元素排序、拖动图表等。它可以改善用户体验,提高网站的吸引力和互动性。

1.19 说一下canvas和svg的区别?

Canvas 和 SVG 都是 HTML5 提供的常见的绘图技术,但两者的实现原理和应用场景却有很大的区别。

  1. 实现原理 Canvas 是基于像素的绘图技术,它通过 JavaScript 操纵画布上的像素来进行绘图。在使用 Canvas 绘图时,我们可以获得一个类似于画布的空间,然后在其上利用数组进行像素点的操作和绘制出需要的图案。而 SVG 采用矢量绘图的方式,也就是基于数学公式,将各种图形和元素的形状、大小、位置等属性通过计算机计算后转化为一条条向量路径,最终表现在屏幕上。
  2. Application scenarios Canvas is more suitable for dynamically displaying a large number of complex graphics or animation effects, such as games, data visualization, poster design, etc., because it can quickly control pixels and has higher flexibility and interactivity. SVG is mainly used for static or fixed-scale graphic drawing, such as icons, logos, vector maps, etc. Since it is in vector form, it will not be distorted when zoomed or deformed. In addition, SVG also provides rich interactive events and CSS style support, and it is more convenient to use SVG for graphic elements that need to be edited and modified.
  3. Performance and maintainability Since Canvas is based on pixel operations and involves a lot of calculation and rendering, it has poor performance compared to SVG when dealing with static graphics drawing. But for large dynamic images and applications that require real-time interaction, Canvas has advantages over SVG. Since SVG constructs graphics based on the XML markup language, the amount of code is larger. When the graphics drawn by SVG become more complex, the maintainability of the code will decrease.

(1) SVG: SVG Scalable Vector Graphics (Scalable Vector Graphics) is a language based on 2D graphics described by the Extensible Markup Language XML. SVG based on XML means that every element in the SVG DOM is available and can be used for a certain elements to attach Javascript event handlers to. In SVG, each drawn shape is considered an object. Browsers can automatically reproduce graphics if the properties of the SVG object change.

Its characteristics are as follows:

  • independent of resolution
  • Support for event handlers
  • Best for applications with large rendering areas (such as Google Maps)
  • High complexity slows down rendering (any app that makes heavy use of the DOM is not fast)
  • Not suitable for gaming applications

(2) Canvas: Canvas is a canvas, which draws 2D graphics through Javascript and renders them pixel by pixel. When its position changes, it will be redrawn.

Its characteristics are as follows:

  • dependent on resolution
  • event handlers are not supported
  • poor text rendering
  • Ability to save resulting images in .png or .jpg format
  • Best for graphics-intensive games where many objects are redrawn frequently

NOTE: A vector diagram, also known as an object-oriented image or a drawing image, is defined mathematically as a series of points connected by lines. Graphical elements in vector files are called objects. Each object is a self-contained entity with attributes such as color, shape, outline, size, and screen position.

To sum up, Canvas and SVG have their own suitable application scenarios, and they need to be selected according to specific business needs. If you need to display some simple fixed patterns or data statistics charts, etc., it is more suitable to use SVG; and if you want to make some interactive animations and games, it is more convenient and effective to use Canvas.

1.20 What are the inline elements? What are block-level elements? What are the empty (void) elements? What is the difference between inline elements and block level elements?

  • Inline elements are:a b span img input select strong
  • Block-level elements are:div ul ol li dl dt dd h1 h2 h3 h4…p
  • empty element:<br> <hr> <img> <input> <link> <meta>
  • Inline elements cannot set width and height, and do not occupy a single line
  • Block-level elements can set the width and height, and occupy a single line

1.21 Talk about your understanding of SSG

SSG (Static Site Generation) refers to pre-generating static pages during construction and deploying these pages to CDN or other storage services to improve the performance and user experience of web applications.

Specifically, the implementation of SSG usually includes the following steps:

  1. In the development phase, use technologies such as template engines to create static page templates;
  2. Obtain the data to be displayed from the background API or through other channels, and fill it into the static page template to generate a complete HTML page;
  3. Use building tools (such as Gatsby, Next.js, etc.) to build static pages and generate static HTML, CSS and JavaScript files;
  4. Deploy the generated static files to the server or CDN for user access.

Compared with traditional dynamic web pages, SSG has the following advantages:

  1. Fast loading: Since the page does not need to be dynamically rendered for each request, SSG can reduce page load time, thereby improving user experience and search engine rankings;
  2. High security: Since there is no background code and database, SSG is not vulnerable to attacks such as SQL injection;
  3. Low cost: SSG can reduce website operation and maintenance costs and server burden because it does not require dynamic servers and other equipment.

It should be noted that SSG is not suitable for scenarios such as frequently updated content and dynamic interaction, but it is a good choice for performance optimization for websites with more stable content and less updates.

1.22 Tell me about web workers?

The role of Web Worker is to create a multi-threaded environment for JavaScript, allowing the main thread to create Worker threads, and assign some tasks to the latter to run.
Once the Worker thread is successfully created, it will always run and will not be affected by activities on the main thread (such as user button click, form submission) interrupt. This is conducive to responding to the communication of the main thread at any time. However, this also causes the Worker to consume more resources and should not be overused, and once used, it should be closed.
Pass the result back to the main thread through postMessage, so that the main process will not be blocked during complex operations
[Ruan Yifeng article] ( Web Worker usage tutorial - Ruan Yifeng's network log (ruanyifeng.com) )

1.23 Tell me about the srcset function of img? What is the difference between alt and title?

  • Responsive pages are often used to set different pictures according to the screen density
  • At this time, the srcset attribute of the img tag is used. The srcset attribute is used to set different screen densities, img will automatically load different pictures
  • alt is the address of the backup image when the image fails, and title is the title of the image

1.24 Talk about your understanding of the Dom tree

What is DOM

The byte stream of the HTML file transmitted from the network to the rendering engine cannot be directly understood by the rendering engine, so it must be converted into an internal structure that the rendering engine can understand. This structure is DOM.

DOM provides a structured representation of HTML documents.

In the rendering engine, DOM has three levels of functions:

  • From the perspective of the page, the DOM is the basic data structure that generates the page.
  • From the perspective of JavaScript scripting, DOM provides an interface for JavaScript scripting operations. Through this set of interfaces, JavaScript can access the DOM structure, thereby changing the structure, style and content of the document.
  • From a security perspective, DOM is a security line, and some unsafe content is rejected during the DOM parsing phase.

In short, DOM is the internal data structure that represents HTML, it connects Web pages and JavaScript scripts, and filters some unsafe content.

How the DOM tree is generated

HTML parser (HTMLParser): Responsible for converting HTML byte streams into DOM structures.

So how does the network process pass data to the HTML parser?

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-1w0cvHXF-1683893094351) (C:\Users\32063\AppData\Roaming\Typora\typora-user-images\ image-20230511155523413.png)]

From the figure, we can know that there is a shared data channel between the network process and the rendering process, and how much data is loaded by the network process, and the data is passed to the HTML parser for analysis.

After the HTML parser receives the data (byte stream), the byte stream will be converted into DOM, the process is as follows:

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-2OHMEm6l-1683893094352) (C:\Users\32063\AppData\Roaming\Typora\typora-user-images\ image-20230511155547442.png)]

There are three stages :

1. Convert the byte stream into Token through the tokenizer. The tokenizer first converts the byte stream into Tokens, which are divided into Tag Token and Text Token.

Note that the Token here is not the Token we understood before, here is a fragment.

2. Token is parsed into a DOM node.

3. Add DOM nodes to the DOM tree.

JavaScript affects DOM generation

We know that JavaScript can modify the DOM, and it will also affect the generation of the DOM.

1. Embedded JavaScript script For example, if we embed a <script>tag code, the previous parsing process is the same, but when the script tag is parsed, the rendering engine judges that it is a script, and the HTML parser will suspend DOM parsing at this time , because The following JavaScript may modify the currently generated DOM structure.

After pausing parsing, the JavaScript engine steps in and executes <script>the script in the tag . After the script is executed, the HTML parser resumes the parsing process and continues to parse the subsequent content until the final DOM is generated.

2. The introduction of JavaScript files is basically the same as before. The difference is that, to execute JavaScript code after pausing the parsing, you need to download this JavaScript code first .

1.25 What is the relationship between Node and Element?

The relationship between Node and Element may be much clearer in terms of inheritance.

Element inherits from Node, has Node's methods, and at the same time expands many of its own unique methods.

In some methods of Element, Node and Element are clearly distinguished. For example: childNodes and children, parentNode and parentElement and other methods.

For some methods of Node, the return value is Node, such as text node, comment node, etc., while for some methods of Element, the return value must be Element.

By distinguishing this point clearly, many low-level problems can be avoided.

ElementSimply put, Node is a base class, and everything in the DOM Text和Commentinherits from it. In other words, Element, Textand Commentare three special Nodes, they are called ELEMENT_NODE, TEXT_NODEand COMMENT_NODE.

So the elements on html that we usually use, that is Element, are of ELEMENT_NODEtype Node.

1.26 What are the reasons for the long loading time of the page and how to optimize it?

1. White screen time

White screen time: It refers to the time from when the screen is blank to when the first screen is displayed after the user clicks a link or opens the browser and enters the URL address.

2. The importance of white screen time

When the user clicks on a link or directly enters the URL in the browser to start accessing, it starts to wait for the page to be displayed. The shorter the page rendering time, the shorter the user waits, and the faster the user perceives the page. This can greatly improve the user experience, reduce user bounce, and improve the retention rate of the page.

3. The process of white screen

The process from inputting url to displaying the screen of the page

1. First, enter url in the browser address bar

2. The browser first checks the browser cache-system cache-router cache. If there is one in the cache, it will directly display the page content on the screen. If not, skip to the third step.

3. Before sending an http request, domain name resolution (DNS resolution) is required to obtain the corresponding IP address.

4. The browser initiates a tcp connection to the server, and establishes a tcp three-way handshake with the browser.

5. After the handshake is successful, the browser sends an http request to the server to request a data packet.

6. The server processes the received request and returns the data to the browser

7. The browser receives the HTTP response

8. Read the content of the page, render it in the browser, and parse the html source code

9. Generate Dom tree, parse css style, js interaction, render and display page

After the browser downloads the HTML, it first parses the header code, downloads the style sheet, and then continues to parse the HTML code downwards, builds a DOM tree, and downloads the style sheet at the same time. When the DOM tree is constructed, immediately start to construct the CSSOM tree. Ideally, the download speed of the style sheet is fast enough, and the DOM tree and the CSSOM tree enter a parallel process. When the two trees are constructed, the rendering tree is constructed and then drawn.

Tips: The impact of browser security parsing policies on parsing HTML:

When inline JS code is encountered when parsing HTML, it will block the construction of the DOM tree, and the JS code will be executed first; when the CSS style file is not downloaded, the browser parses HTML and encounters inline JS code. At this time, the browser Pause JS script execution, pause HTML parsing. Until the download of the CSS file is completed, the construction of the CSSOM tree is completed, and the original parsing is resumed.

JavaScript will block DOM generation, and style files will block the execution of JavaScript. Therefore, in actual projects, you need to focus on JavaScript files and style sheet files. Improper use will affect page performance.

4. White screen - performance optimization

1. DNS resolution optimization

For the DNS Lookup link, we can optimize DNS resolution in a targeted manner.

  • DNS cache optimization
  • DNS Preload Policy
  • Stable and reliable DNS server

2. TCP network link optimization

spend more money

3. Server-side processing optimization

Server-side processing optimization is a very large topic, which will involve Redis cache, database storage optimization, various middleware in the system, and Gzip compression, etc...

4. Browser download, parsing, rendering page optimization

According to the browser's downloading, parsing, and rendering process of the page, you can consider the following optimizations:

  • Streamline HTML code and structure as much as possible
  • Optimize CSS files and structures as much as possible
  • Be sure to place JS code reasonably, try not to use inline JS code
  • Inlining the critical CSS needed to render above-the-fold content into the HTML makes the CSS download much faster. It can be rendered after the HTML download is completed, and the page rendering time is advanced, thereby shortening the rendering time of the first screen;
  • Delay the loading of images that are not required for the first screen, and prioritize the loading of images required for the first screen (offsetTop<clientHeight)
document.documentElement.clientHeight//获取屏幕可视区域的高度
element.offsetTop//获取元素相对于文档顶部的高度

Because JavaScript will block DOM generation, and style files will block the execution of JavaScript, so in the actual project, we need to focus on JavaScript files and style sheet files, improper use will affect page performance.

1.27 Have you ever heard about progressive jpg?

Progressive JPEG (Progressive JPEG), or PJPEG, is one of the standard's three popular compression modes.

Progressive JPEG compresses photos and graphics in a specific way, and unlike baseline JPEG, PJPEG initially gives the appearance of a blurry image when rendered in a web browser. Then it starts rendering the image bit by bit until it shows the fully rendered image. The browser actually interprets the image line by line, but provides a blurry preview of the full image in the placeholder. As the web browser's rendering engine processes the data, the contrast of the image begins to become sharper and more detailed. Until the final rendering is completed, the user will see the complete and clear image.

PJPEG can have a very meaningful psychological effect, allowing users to have something to look at instead of sitting around waiting for a large image to slowly display on the screen.

PJPEG works with most common browsers, including Chrome, Firefoxand Internet Explorer 9and later. Older versions of Internet Explorer had some issues displaying progressive JPEGs, but this was only a small percentage of users. Browsers that do not support the progressive JPEG format will load the photo as a regular JPEG.

1.28 How to realize the function of "click back to the top"?

1. Anchors

Using anchor links is a simple way to return to the top of the function.

This implementation mainly places an anchor link with a specified name at the top of the page, and then places a link back to the anchor at the bottom of the page, and the user clicks the link to return to the top position where the anchor is located.

<body style="height:2000px;">
    <div id="topAnchor"></div>
    <a href="#topAnchor" style="position:fixed;right:0;bottom:0">回到顶部</a>
</body>

2、scrollTop

The scrollTop property indicates the number of pixels to be hidden above the content area.

When the element is not scrolled, the value of scrollTop is 0. If the element is scrolled vertically, the value of scrollTop is greater than 0, and indicates the pixel width of the invisible content above the element

Since scrollTop is writable, scrollTop can be used to achieve the function of returning to the top

<body style="height:2000px;">
    <button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
    <script>
        test.onclick = function(){
            document.body.scrollTop = document.documentElement.scrollTop = 0;
        }
    </script>
</body>

3、scrollTo

The scrollTo(x,y) method scrolls the document displayed in the current window so that the point specified by the coordinates x and y in the document is located in the upper left corner of the display area

Set scrollTo(0,0) to achieve the effect of returning to the top

<body style="height:2000px;">
    <button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
    <script>
        test.onclick = function(){
            scrollTo(0,0);
        }
    </script>
</body>

4、scrollBy()

The scrollBy(x,y) method scrolls the document displayed in the current window, and x and y specify the relative amount of scrolling

As long as the scrolling length of the current page is used as a parameter and scrolling backwards, the effect of returning to the top can be achieved

<body style="height:2000px;">
    <button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
    <script>
        test.onclick = function(){
            var top = document.body.scrollTop || document.documentElement.scrollTop
            scrollBy(0,-top);
        }
    </script>
</body>

5、scrollIntoView()

The Element.scrollIntoView method scrolls the current element into the visible area of ​​the browser

This method can accept a boolean value as a parameter. If true, the top of the element is aligned with the top of the visible part of the current area (if the current area is scrollable); if false, the bottom of the element is aligned with the tail of the visible part of the current area (if the current area is scrollable ). If this parameter is not provided, the default is true

The principle of using this method is similar to that of using anchor points. Set the target element at the top of the page. When the page scrolls, the target element is scrolled out of the page area. Click the back to top button to return the target element to its original position. then achieve the expected effect

<body style="height:2000px;">
    <div id="target"></div>
    <button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
    <script>
        test.onclick = function(){
            target.scrollIntoView();
        }
    </script>
</body>

1.29 How to achieve SEO optimization

SEO is mainly divided into two directions: internal and external.

1. Internal optimization

  • META tag optimization: for example: optimization of TITLE, KEYWORDS, DESCRIPTION (TDK), etc.
  • Optimization of internal links, including related links (Tag tags), anchor text links, navigation links, and image links
  • Website content update: keep the site updated every day (mainly the update of articles, etc.)
  • Server Side Rendering (SSR)

2. External optimization

  • Types of external links: blogs, forums, B2B, news, classified information, post bars, knowing, encyclopedias, related information networks, etc. Keep the diversity of links as much as possible
  • External link operation: Add a certain number of external links every day to make the keyword ranking steadily improve.
  • Selection of external links: exchange friendship links with some websites with high correlation with your website and good overall quality to consolidate and stabilize keyword ranking

1.30 What is SEO?

SEO (Search Engine Optimization), Chinese translation for search engine optimization.

Search engine optimization is a way to use the search rules of search engines to improve the natural ranking of current websites in relevant search engines.

SEO refers to the act of making reasonable planning from the perspectives of website structure, content construction plan, user interaction communication, and pages in order to obtain more free traffic from search engines, so that the website is more suitable for the indexing principles of search engines.

1.31 What is DNS pre-resolution? How to achieve it?

DNS optimization

Before the introduction dns-prefetch, we must first mention the current mainstream methods for DNS optimization.

Generally speaking, a DNS resolution takes 20-120ms, so in order to optimize DNS, we can consider two directions:

  1. Reduce the number of DNS requests
  2. Shorten DNS resolution timedns-prefetch

What is dns-prefetch?

dns-prefetch( DNS prefetch ) is a measure of front-end network performance optimization. According to the rules defined by the browser, it resolves the domain names that may be used in advance, caches the resolution results in the system cache , shortens the DNS resolution time, and improves the website access speed.

Why use dns-prefetch?

Whenever a browser sends a request from a (third-party) server, it must first resolve the cross-domain domain name to an IP address through DNS resolution before the browser can send the request.

If multiple requests are sent to the same server within a certain period of time, DNS resolution will be triggered multiple times and repeatedly. This can cause a delay in overall web page loading.

We know that although DNS resolution does not take up much bandwidth, it will cause high latency, especially for mobile networks.

Therefore, in order to reduce the delay caused by DNS resolution, we can dns-prefetcheffectively shorten the DNS resolution time through pre-resolution technology.

<link rel="dns-prefetch" href="https://baidu.com/"> 

The principle behind dns-prefetch

When a browser accesses a domain name, it needs to resolve the DNS once to obtain the IP address of the corresponding domain name. During parsing, follow:

  • browser cache
  • system cache
  • router cache
  • ISP (operator) DNS cache
  • root name server
  • TLD server
  • primary nameserver

The sequence reads the cache step by step until the IP address is obtained.

dns-prefetchIt is to cache the resolved IP in the system .

In this way, dns-prefetchthe DNS resolution time is effectively shortened. Because, the DNS cache is made in the local operating system, so that the DNS finds the corresponding IP in the system cache in advance during the resolution process.

In this way, subsequent parsing steps do not need to be executed, thereby shortening the DNS parsing time.

If the browser resolves a domain name to an IP address for the first time and caches it in the operating system , the next DNS resolution time can be as low as 0-1ms .

If the result is not cached in the system, then the cache of the router needs to be read , and the subsequent parsing time is at least about 15ms .

If the router cache does not exist, you need to read the ISP (operator) DNS cache . Generally taobao.com, for baidu.comthese common domain names, it takes 80-120ms to read the ISP (operator) DNS cache . If it is an uncommon domain name , takes 200-300ms on average .

Generally speaking, most websites and operators can find the IP.

That is to say, dns-prefetchit can bring a 15-300ms improvement to the DNS resolution process, especially for some websites that refer to a lot of other domain name resources, the improvement effect will be more obvious

Browser DNS cache and dns-prefetch

In order to optimize DNS resolution, modern browsers also have a browser DNS cache.

Its IP is cached every time after the first DNS resolution. As for the cache duration, each browser is different. For example, the expiration time of Chrome is 1 minute, and DNS will not be re-requested within this period.

Tip:
Whenever the Chrome browser is started, it will automatically and quickly resolve the first 10 domain names recorded when the browser was started last time. Therefore, there is no delay in DNS resolution for frequently visited URLs, and the opening speed is faster.

It dns-prefetchis equivalent to doing DNS caching in the local operating system after the browser cache. Personally, it is to guarantee the browser cache and try to let DNS resolve the local, so as to do another layer of DNS resolution optimization. .

Generally speaking, the cache time of DNS in the system is longer than that of the browser.

Browser and system DNS cache time

TTL (Time-To-Live), is the retention time of a domain name resolution record in the DNS server

  • The browser's DNS cache time has nothing to do with the TTL value returned by the DNS server , and its cache time depends on the browser's own settings.
  • The system cache will refer to the TTL value of the DNS server response, but it is not exactly equal to the TTL value .

The TTL value of many domestic and international platforms is in seconds, and the default value of many is 3600, that is, the default cache is 1 hour.

dns-prefetchshortcoming

dns-prefetchThe biggest downside is using it too much.

Excessive pre-fetching will lead to excessive DNS resolution, which is a burden on the network.

Best Practices

Remember the following three points:

  1. dns-prefetchOnly valid for DNS lookups on cross-origin domains, so avoid using it to point to the same domain. This is because, by the time the browser sees the prompt, the IP behind your site's domain has already been resolved.
  2. In addition to link (and other resource hints) can also be specified as HTTP headers by using the HTTP link field :dns-prefetch
Link: <https://fonts.gstatic.com/>; rel=dns-prefetch
  1. Consider pairing dns-prefetchwith a preconnect(preconnect )prompt.

Since dns-prefetchonly performs a DNS lookup, unlike preconnectdoes not establish a connection to the server.

If the site is served over HTTPS, the combination of the two covers DNS resolution, establishing a TCP connection, and performing a TLS handshake. Combining the two provides an opportunity to further reduce the perceived latency of cross-origin requests . As follows:

<link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
<link rel="dns-prefetch" href="https://fonts.gstatic.com/">

Note : If the page needs to establish connections to many third-party domains, it is counterproductive to preconnect them. preconnectHints are best used only for the most critical connections. For the others, just use <link rel="dns-prefetch">a DNS lookup to save time on the first step.

1.32 How to use indexDB

IndexedDB is a browser local database technology, which is different from traditional relational databases or non-relational databases. Its main purpose is to provide a mechanism for web applications to store data on the client side, allowing users to operate offline or cache large amounts of data. case, better performance and reliability.

IndexedDB uses a key-value approach for data storage. Each IndexedDB database consists of multiple object stores (Object Store), and each object store contains a corresponding collection of data records. The following are the basic usage steps:

  1. To open a database, you can open a database with a specified name through the IndexedDB object and its open method, and specify the configuration information of the database, such as version number, object warehouse and index, when creating or upgrading the database.
javascript复制代码// 前提条件:浏览器支持 IndexedDB
let request = indexedDB.open("myDatabase", 2);
request.onerror = function(event) {
  console.log("打开数据库失败");
};
request.onupgradeneeded = function(event) { 
  let db = event.target.result;
  let objectStore = db.createObjectStore("customers", { keyPath: "id" });
  objectStore.createIndex("name", "name", { unique: false });
  objectStore.createIndex("email", "email", { unique: true });
};
request.onsuccess = function(event) {
  let db = event.target.result;
}
  1. Create an object store After opening the IndexedDB database, you can createObjectStore()create an object store by calling the method. You can specify primary keys and indexes to more efficiently manipulate data when querying the database.
javascript复制代码let objectStore = db.createObjectStore("customers", { keyPath: "id" });
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
  1. Adding data records uses transactions to add or update data records. Calling the application's function within a transaction add()commits the data to be stored, specifying which object store it belongs to. It should be noted that all operations in IndexedDB are asynchronous and limited by browser security mechanisms.
javascript复制代码let customerData = [
  { id: 1, name: "John Doe", email: "[email protected]" },
  { id: 2, name: "Jane Doe", email: "[email protected]" }
];
let transaction = db.transaction(["customers"], "readwrite");
let objectStore = transaction.objectStore("customers");
customerData.forEach(function(customer) {
  let request = objectStore.add(customer);
  request.onsuccess = function(event) {
    console.log("新增数据成功");
  };
});
  1. Reading data records Reading a data file is similar to adding a data file. You can also open a transaction and open the corresponding object warehouse, and then use methods such as openCursor()or get()to traverse and obtain the data records in it.
javascript复制代码let transaction = db.transaction(["customers"]);
let objectStore = transaction.objectStore("customers");
let request = objectStore.get(1);
request.onerror = function(event) {
  console.log("读取数据失败");
};
request.onsuccess = function(event) {
  if (request.result) {
    console.log("读取到的数据为:" + JSON.stringify(request.result));
  } else {
    console.log
[Network Error]

1.33 What drag-related APIs does HTML5 have?

  • dragstart: The main body of the event is the dragged and dropped element, which is triggered when the dragged and dropped element starts to be dragged and dropped.
  • darg: The event body is the dragged and dropped element, which is triggered when the dragged and dropped element is being dragged and dropped.
  • dragenter: The event body is the target element, which is triggered when the dragged element enters an element.
  • dragover: The event body is the target element, which is triggered when it is dragged and moved within an element.
  • dragleave: The event body is the target element, and is triggered when the dragged element moves out of the target element.
  • drop: The event body is the target element, which is triggered when the target element fully accepts the dragged and dropped element.
  • dragend: The event body is the element being dragged and dropped, which is triggered when the entire drag and drop operation ends.

1.34 What is the reason for the garbled characters in the browser? How to solve?

Causes of garbled characters:

  • The source code of the webpage is gbkencoded, and the Chinese characters in the content are utf-8encoded, so that garbled characters will appear when the browser is opened html, and garbled characters will appear on the contrary;
  • htmlThe encoding of the web page is gbk, and the program calls out utf-8the content of the encoding from the database, which will also cause garbled encoding;
  • The browser cannot automatically detect the encoding of the web page, resulting in garbled characters on the web page.

Solution:

  • Use software to edit HTML web content;
  • If the encoding of the web page is set to Y gbk, and the encoding format of the data stored in the database is Y UTF-8, at this time, the program needs to query the database data to display the data and advance the program to transcode;
  • If there are garbled characters on the webpage when browsing in the browser, find the conversion code menu in the browser to convert.

1.35 How do js and css affect the construction of the DOM tree?

CSS will not block the parsing of DOM, but it will affect the operation of JAVAScript, javaSscript will prevent the parsing of DOM tree, and finally css (CSSOM) will affect the rendering of DOM tree, and it can also be said that it will eventually affect the generation of rendering tree.

Next, let's first look at how javascript affects the construction and rendering of the DOM tree. It is divided into three types to explain:

JavaScript script in html page

<html>
  <body>
    <div>1</div>
    <script>
      let div1 = document.getElementsByTagName('div')[0]
      div1.innerText = 'time.geekbang'
    </script>
    <div>test</div>
  </body>
</html>

A JavaScript script is inserted between the two divs, and the parsing process of this script is a bit different.

When the script tag is parsed, the HTML parser suspends its work, the javascript engine intervenes, and executes the script in the script tag.

Because this javascript script modifies the content in the first div in the DOM, after executing this script, the content of the div node has been modified to time.geekbang. After the script execution is completed, the HTML parser returns to the parsing process and continues parsing the subsequent content until the final DOM is generated.

Import javaScript files into html pages

//foo.js
let div1 = document.getElementsByTagName('div')[0]
div1.innerText = 'time.geekbang'
<html>
  <body>
    <div>1</div>
    <script type="text/javascript" src='foo.js'></script>
    <div>test</div>
  </body>
</html>

The function of this piece of code is still the same as the previous piece of code, except that the embedded JavaScript script is modified to be loaded through a javaScript file.

The entire execution process is still the same. When the JAVAScript tag is executed, the parsing of the entire DOM is suspended and the javascript code is executed. However, when javascript is executed here, this code needs to be present. Here we need to focus on the download environment, because the download process of the javascript file will block the DOM parsing, and usually the download is very time-consuming and will be affected by factors such as the network environment and the size of the javascript file.

Optimization mechanism:

Google Chrome has done a lot of optimizations, one of the main optimizations is the pre-parsing operation. When the rendering engine receives the byte stream, it will start a pre-parsing thread to analyze the JavaScript, CSS and other related files contained in the HTML file. After parsing the relevant files, it will start a pre-parsing thread to analyze the HTML file. After the javascprit, css and other related files contained in the file are parsed, the pre-parsing thread will download these files in advance.

Going back to DOM parsing, we know that the introduction of JavaScript threads will block the DOM, but there are also some related strategies to avoid, such as using CDN to speed up the loading of JavaScript files and compress the volume of JavaScript files.

In addition, if there is no DOM-related code in the JavaScript file, you can set the JavaScript script to be loaded asynchronously, and mark the code with async or defer. The usage is as follows:

<script async type="text/javascript" src='foo.js'></script>
<script defer type="text/javascript" src='foo.js'></script>

The difference between async and defer:

  • async: The script is loaded in parallel and executed immediately after the loading is completed. The execution timing is uncertain and HTML parsing may still be blocked. The execution timing is before the load event is dispatched.
  • defer: The scripts are loaded in parallel, after the HTML parsing is completed, the scripts are executed in the loading order, before the DOMContentLoaded event is dispatched.

There are css styles in the html page

//theme.css
div {color:blue}
<html>
<head>
    <style src='theme.css'></style>
</head>
<body>
  <div>1</div>
  <script>
      let div1 = document.getElementsByTagName('div')[0]
      div1.innerText = 'time.geekbang' // 需要 DOM
      div1.style.color = 'red' // 需要 CSSOM
  </script>
  <div>test</div>
</body>
</html>

In this example, div1.style.color = ‘red’the statement of appears in the JavaScript code, which is used to manipulate CSSOM, so before executing the JavaScript, it is necessary to parse all the CSS styles above the JavaScript statement. Therefore, if an external CSS file is referenced in the code, before executing JavaScript, it is necessary to wait for the download of the external CSS file to be completed, and to parse and generate a CSSOM object before executing the JavaScript script.

Before the JavaScript engine parses the JavaScript, it does not know whether the JavaScript has manipulated the CSSOM, so when the rendering engine encounters a JavaScript script, no matter whether the script manipulates the CSSOM, it will download the CSS file, parse the operation, and then execute the JavaScript script. So the JavaScript script is dependent on the style sheet, which adds another blocking process.

Summary: Through the analysis of the above three points, we know that JavaScript will block DOM generation, and style files will block the execution of js.

1.36 The difference between readonly and disabled in the form

  • What they have in common: the ability to prevent users from changing the content of the form
  • Differences:
    1. readonly is only valid for input and textarea, but disabled is valid for all form elements, including radio and checkbox
    2. readonly can get the focus, but cannot be modified. The text box set by disabled cannot get the focus
    3. If the field of the form is disabled, the field will not be sent (form value) and serialized

1.37 Mainstream browsers and kernels

Google chrome:webkit/blink
safari:webkit
IE:trident
firefox:gecko
Opera:presto/webkit/blink

1.38 Talk about your understanding of the following page life cycle events: DOMContentLoaded, load, beforeunload, unload

The lifecycle of an HTML page consists of three important events:

  • DOMContentLoaded - The browser has fully loaded the HTML and built the DOM tree, but external resources like styles and style sheets may not have finished loading.
  • load —— The browser has not only loaded the HTML, but also loaded all external resources: pictures, styles, etc.
  • beforeunload/unload - when the user is leaving the page.

Each event is useful:

  • DOMContentLoaded event - The DOM is ready, so the handler can find the DOM node and initialize the interface.
  • load event - external resources have been loaded, styles have been applied, and image sizes are known.
  • beforeunload event - the user is leaving: we can check if the user has saved changes and ask him if he really wants to leave.
  • unload event - the user has almost left, but we can still initiate some actions, such as sending statistics.

DOMContentLoaded and scripts

When a browser processes an HTML document and encounters

Therefore, DOMContentLoaded must occur after the execution of these scripts below.

There are two exceptions to this rule:

  • Scripts with the async attribute don't block on DOMContentLoaded, as we'll see later.
  • Scripts dynamically generated and added to a page using document.createElement('script') will also not block DOMContentLoaded.

DOMContentLoaded and styles

External stylesheets do not affect the DOM, so DOMContentLoaded does not wait for them.

But there's a catch here. If there is a script after the style, the script must wait for the stylesheet to finish loading. The reason is that a script might want to get the element's coordinates and other style-related properties. Therefore, it has to wait for the styles to be loaded.

When DOMContentLoaded waits for scripts, it now also waits for styles preceding scripts.

Browser built-in autofill

Firefox, Chrome and Opera all autofill forms in DOMContentLoaded.

For example, if the page has a form with a login and password, and the browser remembers these values, then on DOMContentLoaded the browser will try to autofill them (if the user allows it).

So if DOMContentLoaded is delayed by a script that takes a long time to load, autofill will also wait. You may have seen this on some sites (if you use browser autofill) - login/password fields are not autofilled immediately, but are filled lazily until the page is fully loaded. This is actually a delay before the DOMContentLoaded event.

window.onload

The load event on the window object is fired when the entire page, including styles, images, and other resources, has been loaded. This event can be obtained through the onload attribute.

window.onunload

When the visitor leaves the page, the unload event on the window object is fired. We can do things there that don't involve a delay, like closing the associated popup.

One notable special case is sending analytics data.

Suppose we collect data about page usage: mouse clicks, scrolling, areas of the page viewed, etc.

Naturally, when the user is about to leave, we want to save the data to our server via the unload event.

There is a special navigator.sendBeacon(url, data) method to meet this requirement, see the specification https://w3c.github.io/beacon/ for details.

It sends data in the background, and there is no delay in transitioning to another page: the browser leaves the page, but still executes sendBeacon.

By the time the sendBeacon request completes, the browser may have left the document, so there is no way to get the server response (which is usually empty for analytics data).

There is also a keep-alive flag, which is used in the fetch method to perform such "after leaving the page" requests for generic network requests. You can find more information about it in the Fetch API chapter.

If we want to cancel the operation of jumping to another page, we can't do it here. But we can use another event - onbeforeunload.

window.onbeforeunload

If the visitor triggers navigation away from the page or attempts to close the window, the beforeunload handler will ask for more confirmation.

If we want to cancel the event, the browser will ask the user if they are sure.

Summarize

Page lifecycle events:

  • When the DOM is ready, the DOMContentLoaded event on the document is fired. At this stage, we can apply JavaScript to the element.
    • Scripts such as <script>...</script>or <script src="..."></script>block on DOMContentLoaded, and the browser waits for them to finish executing.
    • Images and other resources can still continue to be loaded.
  • When the page and all resources are loaded, the load event on the window is fired. We rarely use it because there is usually no need to wait that long.
  • When the user wants to leave the page, the beforeunload event on the window is fired. If we cancel this event, the browser will ask us if we really want to leave (for example, we have unsaved changes).
  • When the user finally leaves, the unload event on the window is fired. In handlers, we can only perform simple actions that don't involve delays or asking the user. It is because of this limitation that it is rarely used. We can use navigator.sendBeacon to send network requests.

1.39 When using the input tag to upload pictures, how to trigger the default camera function?

The capture property is used to specify how the media is captured in the file upload control.

Optional values:

  • user prefix
  • environment post
  • camera camera
  • camcorder camera
  • microphone recording
<input type='file' accept='image/*;' capture='camera'>

Upload multiple photos to input

<input type="file" name="files" multiple/>

1.40 How to prohibit the input from displaying the input history?

When entering the input, it will prompt the original input content, and there will also be a drop-down history record. To prohibit this situation, just add in the input: autocomplete="off"

<input type="text"  autocomplete="off" />

The autocomplete attribute is used to specify whether the input field is enabled for auto-completion.

1.41 What is iconfont? What are the pros and cons?

What is IconFont

As the name suggests, IconFont is a font icon. Strictly speaking, a typeface, however, instead of letters or numbers, they contain symbols and glyphs. You can style it with CSS just like regular text, making IconFont a popular choice for icons when developing for the web.

advantage

  • You can easily apply any CSS effect to them.
  • Because they are vector graphics, they are scalable. This means we can scale them without losing quality.
  • We only need to send one or a few HTTP requests to load them, not like images, which may require multiple HTTP requests.
  • They load fast due to their small size.
  • They are supported in all browsers (even up to IE6).

insufficient

  • Cannot be used to display complex images
  • Usually limited to one color unless some CSS tricks are applied
  • Font icons are usually designed according to a specific grid, such as 16x16, 32x32, 48x48, etc. If you change the grid system to 25×25 for some reason, you may not get crisp results

1.42 What are the commonly used PV and UV indicators in page statistics?

PV (Page Views)

That is, the number of page views or clicks. Every time a user visits each web page in the website, a PV is recorded.

The user visits the same page multiple times, and the number of visits is accumulated, which is used to measure the number of web pages visited by website users.

UV (unique visitor)

Refers to the natural person who visits and browses this webpage through the Internet. A computer client accessing your website is a visitor.

The same client within 00:00-24:00 is only counted once.

1.43 Is the dpr of a device variable?

devicePixelRatio, the Chinese name is the device pixel ratio. This concept will receive special attention during mobile development, because it is related to the look, feel, layout and even clarity of the entire screen. In JavaScript BOM, it is a property under the window global object, and its definition is as follows:

dpr = device pixels / CSS pixels

There are also articles that refer to device pixels as physical pixels and CSS pixels as independent pixels (DIPs), but they all refer to the same concept:

(1) Let's talk about device pixels first. Taking mobile phones as an example, the device pixels are 1920 1080 pixels or 1280 720 pixels that are often seen in mobile phone advertisements , which is often referred to as 1080p or 720p resolution. It refers to how many minimum areas on the device can display a specific color, and this value will not change in any device.

(2) Let's talk about CSS pixels, which is called an independent pixel in a broader sense. CSS pixels are created for web developers and are an abstraction layer used in CSS and JavaScript. The properties we define in CSS, such as width: 100px; and font-size: 16px;, all refer to CSS pixels. Compared with CSS pixels, the concept of device pixels is hardly used in the front end (except for screen.width/height).

Then, from the definition point of view, the meaning of dpr is: on a device (in each direction), how many actual physical pixels will be displayed by each CSS pixel.

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-1K453lNx-1683893094352) (C:\Users\32063\AppData\Roaming\Typora\typora-user-images\ image-20230512093200340.png)]

In the image above, a blue square represents a device pixel, and a yellow square represents a CSS pixel. We can clarify the concept of dpr through this picture:

  • As shown on the left, one device pixel covers multiple CSS pixels, dpr < 1, corresponding to the user's zoom-out operation;
  • As shown on the right, one CSS pixel covers multiple device pixels, dpr > 1, corresponding to the user's zoom-in operation.

Since the user's zoom operation changes the dpr , the device dpr is defined with a default zoom of 100%.

1.44 What are the image loading and rendering rules in html and css?

The web browser first parses the acquired HTML code into a DOM tree. Each tag in the HTML is a node in the DOM tree, including the hidden tags with display: none, and the elements dynamically added by JavaScript. The browser will obtain all the styles and parse them into style rules, and remove the styles that the browser cannot recognize during the parsing process.

The browser will combine the DOM tree and style rules (DOM elements and style rules match) and then build a rendering tree (Render Tree). The rendering tree is similar to the DOM tree, but there is still a big difference between the two: rendering The tree can identify styles, each node (NODE) ​​in the rendering tree has its own style, and the rendering tree does not contain hidden nodes (such as display:none nodes, and some nodes inside), because these nodes will not use For rendering, it will not affect the rendering of nodes, so it will not be included in the rendering tree. Once the render tree is built, the browser can draw the page according to the render tree.

A simple summary is that the browser will go through six processes when rendering a Web page:

  • Parse HTML to form a DOM tree
  • Parse the loaded style and build a style rule tree
  • Load JavaScript, execute JavaScript code
  • The DOM tree and the style rule tree are matched to form a rendering tree
  • Calculate element position for page layout
  • Draw the page and finally render it in the browser

Do you feel that this has nothing to do with our image loading and rendering, but this is not the case, because img, picture or background-image are all part of the DOM tree or style rules, so when we apply them, there are timings for image loading and rendering It could be something like this:

  • When parsing HTML, if an img or picture tag is encountered, the image will be loaded
  • Parse the loaded style, when encountering background-image, the image will not be loaded, but a style rule tree will be built
  • Load JavaScript and execute JavaScript code. If there is an img element created in the code, it will be added to the DOM tree; if there is a background-image rule added, it will be added to the style rule tree
  • Build the rendering tree when the DOM tree matches the style rule, and if the DOM tree node matches the backgorund-image in the style rule, the background image will be loaded
  • Calculate element (image) position for layout
  • Start rendering the image, and the browser will render the rendered image

The browser's page rendering mechanism is applied above, but there are still certain rules for image loading and rendering. Because, not all (or picture) elements on the page will load the pictures and the background pictures introduced by background-image. Then a new question arises, when will it actually load, and what are the loading rules?

To summarize a bit:

Not all images in a web page will be loaded and rendered!

According to the browser loading and rendering mechanism introduced earlier, we can summarize it as:

  • , and when an element with background-image encounters display:none, the image will be loaded but not rendered
  • , and setting display:none on the ancestor element of the element that sets the background-image, the background-image will not be rendered or loaded, while the pictures introduced by img and picture will not be rendered but will be loaded
  • , and background-image import the same path and the same image file name, the image will only be loaded once
  • If the image introduced by background-image in the style file cannot match the DOM element, the image will not be loaded
  • The background-image introduced by the pseudo-class, such as :hover, will only load when the pseudo-class is triggered.

1.45 What is the use of the viewport in the mete tag?

What is Viewport?

The viewport is the viewable area of ​​the user's web page .

The translation of viewport into Chinese can be called **"viewport"**.

The mobile browser puts the page in a virtual "window" (viewport), usually the virtual "window" (viewport) is wider than the screen, so that each web page does not need to be squeezed into a small window (this will Breaking the layout of web pages that are not optimized for mobile browsers), users can pan and zoom to see different parts of the web page.

Set Viewport

A commonly used viewport meta tag for a page optimized for mobile web pages is roughly as follows:

1<meta name="viewport" content="width=device-width, initial-scale=1.0">
  • Width: Control the size of the viewport, you can specify a value, such as 600, or a special value, such as device-width is the width of the device (the unit is CSS pixels when the zoom is 100%).
  • height: Corresponding to width, specify the height.
  • initial-scale: The initial zoom ratio, that is, the zoom ratio when the page is loaded for the first time.
  • maximum-scale: The maximum scale the user is allowed to zoom to.
  • minimum-scale: The minimum scale the user is allowed to zoom to.
  • user-scalable: whether the user can manually scale.

1.46 How to choose the image format at the front end

There are currently two types of images:

  • bitmap
  • vector illustration

bitmap

The so-called bitmap is a picture made up of pixels, also called a bitmap. The png, jpg and other pictures we usually use are bitmaps.

vector illustration

Vector graphics, also known as vector graphics. Vector graphics do not record the information of every point on the screen, but record the algorithm of the shape and color of the elements. When you open a vector diagram, the software performs calculations on the functions corresponding to the graphics, and calculates the shape and color of the graphics as a result of the calculation. Show it to you.

Regardless of whether the display screen is large or small, the algorithm corresponding to the objects on the screen is unchanged, so even if the screen is scaled by a considerable multiple, it will not be distorted like a bitmap.

The most common is the svg format.

image compression type

  • no compression
  • lossy compression
  • lossless compression

no compression

The uncompressed image format does not compress the image data and can accurately present the original image. For example, pictures in BMP format.

lossy compression

It means that in the process of compressing the file size, part of the information of the picture is lost, that is, the quality of the picture is reduced (that is, the picture is blurred), and this loss is irreversible.

A common lossy compression method is to combine adjacent pixels according to a certain algorithm. The compression algorithm does not encode and compress all the data of the picture, but removes the details of the picture that cannot be recognized by the human eye during compression. Therefore, lossy compression can greatly reduce the size of the image with the same image quality. For example, pictures in jpg format use lossy compression.

lossless compression

In the process of compressing pictures, there is no loss in picture quality. We can restore the original information from lossless compressed pictures at any time.

The compression algorithm encodes and compresses all the data of the picture, which can reduce the volume of the picture while ensuring the quality of the picture. For example, png and gif use lossless compression.

Image Bits

Picture bits are usually divided into 8, 16, 24, 32

  • The larger the number of bits in the picture, the more colors it can represent, and the larger the volume it occupies. For example, 8-bit images support 256 colors, which is 2 to the 8th power.
  • The larger the number of image bits, the more delicate the color transition will be, and the color information carried can be richer.
  • The difference between 32-bit and 24-bit is that there is an additional Alpha channel to support translucency, and the others are basically the same as 24-bit.

common image formats

GIF

The full name of GIF is GIF Graphics Interchange Format, which can be translated into Graphics Interchange Format. It was developed by Compu Serve in 1987 to fill the gap in cross-platform image formats.

GIF uses the Lempel-Zev-Welch (LZW) compression algorithm, which supports up to 256 colors. Due to this characteristic, GIF is more suitable for pictures with less color, such as cartoon shapes, company logos and so on. If you encounter occasions that require 24-bit true color, then the expressiveness of GIF is limited.

The biggest feature of GIF format pictures is frame animation, which is smaller in size compared to the old bmp format, and supports transparency (does not support translucency, because Alpha transparency channel is not supported) and animation.

advantage:

  • small volume
  • support animation

shortcoming:

  • Due to 8-bit compression, only up to 256 colors can be processed

JPEG/JPG

JPEG is Joint Photographic Experts Groupthe abbreviation of (Joint Photographic Experts Group), and the file suffix name is ".jpg" or ".jpeg". It is a commonly used image file format and is formulated by a software development association. It is a lossy compression format. The image can be compressed in a small storage space, and repeated or unimportant data in the image will be lost, so it is easy to cause damage to the image data. In particular, if the compression ratio is too high, the quality of the restored image after decompression will be significantly reduced. If you pursue high-quality images, you should not use an excessive compression ratio.

advantage:

  • Using lossy compression, the compressed volume is smaller
  • Support 24-bit true color
  • Support for progressive loading

shortcoming:

  • Lossy compression can damage the quality of the image
  • Does not support transparency/translucency

Progressive jpeg (progressive jpeg)

Progressive jpg files contain multiple scans that are sequentially stored in the jpg file. In the process of opening the file, the blurred outline of the entire picture will be displayed first, and the picture will become clearer and clearer as the number of scans increases.

PNG

png, or Portable Network Graphics, is a lossless compressed bitmap graphic format designed to replace the GIF and TIFF file formats while adding some features that the GIF file format does not have. PNG uses a lossless data compression algorithm derived from LZ77, and is generally used in JAVA programs, web pages or S60 programs because of its high compression ratio and small file size.

PNG supports 8-bit, 24-bit, and 32-bit. We usually call them png8, png24, and png32.

advantage:

  • lossless compression
  • Support transparent, translucent
  • Up to 24-bit true color images and 8-bit grayscale images are supported, thereby completely eliminating jagged edges.

shortcoming:

  • PNG offers less compression than jpg's lossy compression
  • Does not support animation, if you need to support animation, you have to use apng

APNG

APNG (Animated Portable Network Graphics) is a bitmap animation format based on PNG (Portable Network Graphics). In fact, it is an animation composed of multiple pngs. Open the MAC computer and you can see every picture that makes up apng.

advantage:

  • Supports all the advantages of png
  • support animation

shortcoming:

  • Browser support is poor

WEBP

WebP was originally released by Google in 2010 with the goal of reducing file size. It supports both lossless and lossy compression.

It almost integrates the advantages of all the above pictures, and can have a higher compression rate, but the browser support rate is not ideal enough.

SVG

SVG is a language defined in XML for describing two-dimensional vector and vector/raster graphics. SVG provides three types of graphic objects: vector graphics (for example: paths composed of straight lines and curves), images, and text. Graphics objects can also be grouped, styled, transformed, combined, and more. The feature set includes nested transformations, clipping paths, alpha masks, filter effects, template objects, and other extensions.

SVG graphics are interactive and dynamic, and you can embed animation elements in SVG files or define animations through scripts.

The difference between SVG and the above picture is that it is a vector diagram, no matter how you zoom in, it will not be distorted; at the same time, SVG files are usually much smaller than JPEG and PNG format files.

advantage:

  • SVG can be read and modified by many tools (such as Notepad)
  • SVG is smaller and more compressible than JPEG and GIF images.
  • SVG is scalable
  • SVG images can be printed with high quality at any resolution
  • SVG can be scaled up without loss of image quality
  • SVG can run with JavaScript technology
  • SVG files are pure XML

shortcoming:

  • The rendering cost is relatively high compared to other format images, which has an impact on performance.
  • There is a learning cost as SVG is a language defined in XML.

How to choose the format of the picture

img

Guess you like

Origin blog.csdn.net/hyqhyqhyqq/article/details/130649363