Preface πŸ’¬

Usually when we load a web page, we first need to load the code of the web page, and then render the page, during which several JS will be executed. Therefore, if we want fast rendering and fast rendering of web pages, we need to make our code stable and efficient in the browser runtime environment. This brings us to the issue of front-end performance optimization.

This article will explain some common questions about performance optimization

πŸ’― Mind map first look

Let’s start with a mind map to comb through the knowledge points.See πŸ‘‡ below for details

The mind map is in the bag. Now, let’s look at some common interview questions

πŸ‘οΈπŸ—¨οΈ 1. HTML, CSS, JS, jQ optimization

1. How to optimize performance for HTML?

Specific methods are as follows:

(1) For resource loading, on-demand loading and asynchronous loading.

(2) the resources loaded for the first time do not exceed 1024KB(1 MB), that is, the smaller the better.

(3) Compress HTML, CSS, JavaScript files.

(4) Reduce DOM nodes.

(5) Avoid empty SRC (empty SRC can cause invalid requests in some browsers).

(6) Avoid request errors 30, 40, 50.

Add favicon. ico. If no icon ico is set, the default icon will cause a 404 or 500 request to be sent.

2. How to optimize the performance of CSS?

Specific optimization methods are as follows:

(1) Correctly use display attribute, display attribute will affect the page rendering, so pay attention to the following aspects.

Display: Inline should no longer be used after width, height, margin, padding, and float. Display: Float should not be used after inline-block. Display: Vertical-align should not be used after block. Margin or float should not be used after display:table-*.Copy the code

(2) Do not abuse float.

(3) Do not declare too much font size.

(4) When the value is 0, no unit is needed.

(5) Place the style sheet at the top of the page.

(6) Use less and SCSS expressions.

(7) Use link instead of @import to introduce styles.

  • link 是 HTMLWay,@import 是 CSSWay;
  • linkMaximum support for parallel downloads,@importToo much nesting will result in serial downloads that will occurFOUC(Document style is temporarily invalid);
  • The browser tolinkSupport earlier than@import, you can use@importHide styles from older browsers
  • In general:linkBetter than@importAnd,linkAnd a higher priority.

(8) Try to use id and class selectors to set styles (avoid using the style attribute to set inline styles).

(9) Standardize various browser prefixes and pay attention to the following aspects:

  • Browser without prefix should be placed last.
  • CSSAnimation can only be (-webkit- and no prefix).
  • Other prefixes include -webkit-, -moz-, -ms-, and no prefixes (Opera switched to blink kernel, so -0- was eliminated).

(10) Avoid making selectors look like regular expressions. Advanced selectors are not easy to read and take a long time to execute.

(11) It is forbidden to use GIF images to achieve loading effect, and CSS3 animation is used as far as possible to achieve loading effect (reduce CPU consumption and improve rendering performance).

(12) Use CSS3 code instead of JS animation to avoid redrawing and reflow as much as possible.

3. What methods can improve CSS3 animation experience on mobile terminal?

(1) Make use of hardware capabilities as much as possible, such as using 3D deformation to enable GPU acceleration, such as the following code.

-webkit-transform: translate3d(0.0.0);
-moz-transform : translate3d(0.0.0);
-ms-transform : translate3d(0.0.0);
transform: translate3d(0.0.0);
Copy the code

Moving an element 500PX to the right with translate3D is much better than moving an element 500PX to the right with the left attribute because the CSS attribute triggers the entire page to be rearranged, redrawn, and reorganized.

Paint is usually the most performance-efficient, so avoid using the CSS animation properties that trigger paint whenever possible.

If there is a flicker during animation execution (usually at the beginning of the animation), it can be handled as follows.

-webkit-backface-visibility:hidden;
-moz-backface-visibility:hidden;
-ms-backface-visibility:hidden;
backface-visibility:hidden;
-webkit-perspective:1000;
-moz-perspective:1000;
-ms-perspective:1000;
perspective:1000;
Copy the code

(2) Use box-shadows and gradients as little as possible, they tend to seriously affect page performance, especially if they’re all in the same element.

(3) Keep animation elements out of the document flow as much as possible to reduce rearrangements, as shown in the code below.

position:fixed;
position:absolute;
Copy the code

4. How to optimize performance for JavaScript?

(1) Selection and calculation of cache DOM.

(2) Try to use the event delegation mode to avoid batch binding events.

(3) Use TouchStart and touchend instead of click.

(4) Use requestAnimation Frame instead of setTimeOut properly.

(5) Canvas animation is properly used.

(6) Try to avoid modifying views in high-frequency events (such as TouchMove and Scroll events), which will lead to multiple rendering.

5. How to optimize jQuery performance?

(1) Use the latest versionjQueryThe class library

  • JQueryEach new version of the library contains Bug fixes and optimizations for the previous version, as well as innovations, so it is recommended to use the latest versionjQueryClass libraries improve performance. Note, however, that don’t forget to test your code after you change versions, because sometimes it’s not fully backward compatible.

(2) Use the appropriate selector

  • jQueryProvides a very rich selection of selectors. Selectors are the most commonly used feature for developers, but using different selectors can also cause performance problems. The following selectors are recommended, for exampleidSelectors, class selectors, and do not placeidSelector nesting and so on.

(3) Use it as an arrayjQueryobject

  • usejQueryThe result of the selector is onejQueryObject. However,jQueryClass libraries make you feel like you’re using a definitionThe indexandThe length of theThe array. In terms of performance, simple is recommendedfororwhileLoop to process instead of$. each()“, which makes the code faster.

(4) Use the event delegate mode

  • eachJavaScriptEvents (e.g.click,mouseoverEtc.) will bubble upThe parent node. When you need to bind multiple elementsSame callback functionIs recommendedEvent delegation pattern.

(5) Join strings using join()

  • usejoin()Concatenate long strings instead of using"+"Concatenate strings, which helps with performance optimization, especially when dealing with long strings.

(6) Make reasonable use of data attribute in HTML5

  • HTML5In thedataAttributes are useful for inserting data, especially for front – and back-end data exchange;
  • jQuery ηš„ data()The method can be used effectivelyHTML5Property to automatically retrieve data.

πŸ—¨οΈ 2. Optimization of website and mobile terminal

Talk about your understanding of refactoring.

Website refactoring is the act of simplifying structure, adding readability, and maintaining consistency at the front end of a website without changing the external behavior. That is, optimize the site without changing the UI, and maintain a consistent UI while extending it.

For traditional web sites, refactoring usually involves the following aspects.

  • Change the table layout todiv+css 。
  • Make the front end compatible with modern browsers.
  • Optimize the mobile platform.
  • Optimize for search engines.

Deep site refactoring should consider the following aspects.

  • Reduce coupling between codes.
  • Keep your code elastic.
  • Code strictly to specifications.
  • Design extensibleAPI 。
  • Replace old frameworks, languages (e.gVB).
  • Enhance the user experience.
  • Optimize speed.
  • The compressionJavaScript, CSS, imageAnd other front-end resources (usually byThe serverTo solve).
  • Optimize program performance (such as data reads and writes).
  • usingCDNTo speed up resource loading.
  • To optimize the JavaScript DOM 。
  • The cacheHTTPServer files.

2. List Web performance optimization methods you know.

Specific optimization methods are as follows:

  • Compress source code and images.
    • JavaScriptUsing obfuscation compression;
    • CSSOrdinary compression;
    • JPGThe picture is compressed according to the specific quality50% ~ 70%,PNGFrom the picture24 colorCompressed into8 colorsTo get rid of somePNGFormat information etc.).
  • Choose the right image format (multiple colors)JPGFormat, while rarely usedPNGFormat, if the server side can determine browser supportWebPJust useWebP ζˆ– SVGFormat).
  • Merge static resources (reducedHTTPRequest).
  • The multipleCSSMerge into oneCSS, combine the pictures intoSprite figure.
    • What is a Sprite? What are the advantages?
    • Sprite, also known as Sprite, refers to combining multiple images into one image to reduce the total size of the image.
    • After combining multiple images into one image, all required resources can be downloaded with only one network request, reducing the consumption of establishing connections, especially in mobile terminals.
  • Enabling the serverGzipCompression (very effective for text resources).
    • How does Gzip compress files?
    • gzipFor files to be compressed, use firstLZ77A variant of the algorithm is compressed and the results are reusedHuffmanMethod of coding.
  • useCDN(Shared cache for public libraries).
    • What is CDN?
    • CDNContent delivery networks.
    • The basic idea is to avoid the bottlenecks and links that may affect the speed and stability of data transmission on the Internet as far as possible, so that the content transmission is faster and more stable.
    • How to use CDN?
    • Buy from a cloud service providerCDNService, for later useCDNLoad static resources.
  • Prolong the static resource cache time.
  • theCSSPut it at the top of the pageJavaScriptThe code is placed at the bottom of the page (to avoid blocking the page rendering and leaving the page blank for a long time).

3. How to optimize the performance of mobile terminal?

The optimization method is as follows.

  • Try to useCSS3Animation, onHardware acceleration.
  • Appropriate use oftouchEvents instead ofclickEvents.
  • Avoid the use ofCSS3Gradient shadow effect.
  • You can usetransform:translateZ(0)To enable hardware acceleration.
  • Don’t abuseFloat , FloatIn the rendering calculation is relatively large, use as little as possible.
  • Don’t abuseWebFont,WebFonts need to be downloaded, parsed, redrawn and used sparingly.
  • The rational use ofrequestAnimation FrameAnimation instead ofsetTimeout 。
  • The rational use ofCSSAttributes in (CSS3 transitions 、 CSS3 3D transforms 、 Opacity 、 Canvas 、 WebGL 、Video) to trigger GPU rendering. Overuse can increase your phone’s power consumption.

4, what methods can improve the front-end performance of the website?

  • Wizard graph merge, reduce HTTP requests;
  • The compressionHTML, CSS, JavaScriptFile;
  • useCDNHosting static files;
  • uselocalstorageCaching andmainfestApply caching.

5. Talk about performance optimization.

Performance can be optimized at the following levels.

  • Cache utilization: the cacheAjax, the use ofCDNOutside,JavaScript ε’Œ CSSFile cache, addExpiresHeader, configured on the server sideEtagTo reduceDNSSearch, etc.
  • The number of requests: Merges styles and scripts, usingCSSPicture wizard, the initial first screen outside the picture resources on demand loading, static resources lazy loading.
  • Request bandwidth: Compressed files, openGZIP 。
  • CSS code: Avoid usingCSSExpression, advanced selector, wildcard selector.
  • JavaScript code:Hash tableTo optimize the search, use lessThe global variablewithinnerHTMLInstead ofDOMOperation, reduceDOMNumber of operations, optimizationJavaScriptPerformance,setTimeoutAvoid page loss of response, cachingDOMNode lookup results, avoid usingwith(withWill create its own scope, increase the length of the scope chain), multiple variable declarations merge.
  • The HTML code: Avoid pictures andiFrame η­‰ srcProperty is null.srcProperty is empty, will reload the current page, affecting speed and efficiency, try to avoid inHTMLLabel in writingStyleProperties.

6. If there are a large number of pictures on a page (large e-commerce website) and the page loading is very slow, what methods can be used to optimize the loading of these pictures, so as to improve the user experience?

  • For image lazy loading, you can add a scroll bar event to the page to determine whether the image is in the viewable area or about to enter the viewable area.
  • If it is a slide, album file, etc., you can use the image preloading technology to download the image before and after the current picture.
  • If the picture isCSSPictures can be usedCSS Sprite 、 SVG sprite 、 iconfont 、 Base64Such as technology.
    • When do you code in Base64?
    • Use Base64 encoding when images are small enough to be reused multiple times.
    • Note: 1.Use of large imagesbase64Encoding may increase the size of the original imageA third, sobase64Encoding does not work for large images.2.usebase64Encoding images does not mean performance optimization.
  • If the image is too large, you can use a specially encoded image, which will be loaded with a thumbnail that is compressed to a very small size to improve the user experience.
  • If the image display area is smaller than the actual size of the image, compress the image on the server based on service requirements. After the image compression, the image size is consistent with that on the display.

7. How to optimize the files of the website?

  • Can be file merge, file compression to minimize the file;
  • You can useCDNHosting files for faster user access;
  • You can use multiple domain names to cache static files.

Name some ways to shorten page load time.

Specific methods are as follows:

(1) Optimize the picture.

(2) Select the image storage format (for example, GIF provides fewer colors and can be used in some places where color requirements are not high).

(3) Optimize CSS (compress and merge CSS).

(4) Add a slash after the url.

(5) Specify the height and width of the image (if the browser does not find the height and width parameters, it needs to calculate the size as it downloads the image. If there are many images, the browser needs to constantly adjust the page. This affects not only speed, but also the browsing experience. When the browser knows the height and width parameters, even if the image cannot be displayed for a while, it will make space for the image on the page and continue to load, optimizing the loading time and improving the browsing experience).

9. What do you know about optimizing performance?

The specific methods are as follows.

(1) reduce the number of HTTP requests, control CSS Sprite, JavaScript and CSS source code, the size of the picture, the use of web Gzip, CDN hosting, data cache, picture server.

(2) Reduce the bandwidth waste caused by HTML tags through front-end template JavaScript and data, and save Ajax request results with variables in the front-end. When operating local variables, no request is required and the number of requests is reduced.

(3) Use innerHTML instead of DOM operations to reduce DOM operations and optimize JavaScript performance.

(4) When there are many styles to set, set className instead of Style.

(5) Less use of global variables, cache DOM node search results, reduce I/O read operations

(6) Avoid using CSS expressions, also known as dynamic attributes.

(7) Preload the image, put the style sheet at the top, the script at the bottom, and timestamp it.

Avoid using tables in the main layout of a page. Tables are not displayed until the content is fully loaded, which is slower than DIV+CSS layout.

What do you know about SEO search engine optimization methods?

  • reasonabletitle 、description 、keywords :
    • The weights of the search terms decrease one by one,titleValue to emphasize the focus can be, important keywords do not appear more than 2 times, and to the front, different pagestitleBe different;
    • descriptionThe page content is highly summarized, the length is appropriate, not excessive stacking keywords, different pagesdescriptionMake a difference;
    • keywordsJust list the key words.
  • The semanticHTMLCode, accord withW3CSpecification: Semantic code makes web pages easy for search engines to understand.
  • Important contentHTMLCode comes first: search engine crawlsHTMLFrom top to bottom, some search engines are rightGrab the lengthThere are limits to ensure that important content will be captured.
  • Don’t use important contentjsOutput: Crawler does not executejsGet content.
  • To use lessiframe: Search engines don’t crawliframeThe content of.
  • Non decorative pictures must be addedalt.
  • Improve site speed: Site speed is an important indicator of search engine ranking.

πŸ—―οΈ 3. Code and server-side optimization

1. How do you usually optimize your code for performance?

(1) Use performance analysis tools to monitor performance, including the static Analyze tool and the Profile tool at run time (start by clicking the Product→ Profile item in the Xcode toolbar).

(2) For example, test the running Time of the application. When the Time Profiler TAB is clicked and the application starts running, you can get the distribution and percentage of the Time spent running the entire application. To ensure the authenticity of data analysis in the same usage scenario, it is important to use a real machine because the emulator is running on a Mac, which tends to have a faster CPU than iOS devices.

2. How to optimize the server side?

Specific methods are as follows:

(1) Enable Gzip compression for components.

(2) Prolong the resource cache time and reasonably set the expiration time of resources. For some static resources that are not updated for a long time, the expiration time can be set longer.

(3) Reduce the size of cookie header information. The larger the header information is, the slower the resource transmission speed is.

(4) Images, CSS and JavaScript files can be accelerated by CDN.

3. How to optimize the server-side interface?

Specific methods are as follows:

(1) Interface merge: if a page needs to request more than two parts of the data interface, it is recommended to merge into one to reduce the number of HTTP requests.

(2) Reduce the amount of data: remove unnecessary data from the data returned by the interface.

(3) Cache data: cache data after the first loading request; For non-initial requests, the data of the last request is used preferentially to improve the response speed of non-initial requests.

4. How to optimize script execution?

Improper script handling will block page loading and rendering, so be careful when using it.

(1) Write CSS in the page header, write JavaScript programs in the page tail or asynchronous operation.

(2) Avoid empty SRC of images and iframes, which will reload the current page, affecting speed and efficiency.

(3) Try to avoid resetting the image size. Resize an image multiple times in a page, CSS, JavaScript file, etc. Resize an image multiple times will cause multiple redraws of the image, affecting performance

(4) Avoid using DataURL for images. DataURL images do not use the image compression algorithm, the file will become large, and to be decoded after rendering, loading is slow, time-consuming.

5. What are the optimization methods for page rendering?

Specific methods are as follows:

(1) Set the Viewport meta tag through HTML, Viewport can speed up the page rendering, as shown in the following code.

<meta name="viewport" content="width=device=width,initial-scale=1">
Copy the code

(2) Reduce the number of DOM nodes. Too many DOM nodes will affect page rendering, so the number of DOM nodes should be reduced as much as possible.

(3) Try to use CSS3 animation, rationally use requestAnimation Frame animation instead of setTimeout, appropriately use Canvas animation (CSS animation is used within 5 elements, Use Canvas animation for more than 5 elements (webGL is available in iOS 8).

(4) Optimize Touchmove for high-frequency events, Scroll events can lead to multiple rendering.

  • userequestAnimation FrameListen for frame changes to render at the correct time, increase the time between responses to changes, and reduce redraw times.
  • Use throttling mode (throttling based on operation or throttling based on time) to reduce the number of triggers.

(5) Improve the GPU speed, using CSS properties (CSS3 Transitions, CSS3 3D Transforms, Opacity, Canvas, WebGL, Video) to trigger GPU rendering.

6. How to set DNS cache?

After entering the URL in the address box of the browser, the browser must first query the server IP address corresponding to the hostname domain name, which usually takes 20 to 120ms.

The browser does not recognize the server IP until the DNS query is complete, so it does not download any data. Based on performance considerations, ISP operators, LAN routes, operating systems, and clients (browsers) all have corresponding DNS caching mechanisms.

(1) Positive IE cache for 30min, which can be set by DnsCacheTimeout in the registry.

(2) the Firefox stored under 1 min, through the network. The dnsCacheExpiration configuration.

(3) In Chrome, click “Settings” β†’ “Options” β†’ “Advanced Options” and select “improve web page loading speed by pre-extracting DNS” to configure the cache time.

7. When will a resource access failure occur?

During development, it was found that many developers did not set the icon and the server root directory did not hold the default favicon.ico, resulting in request 404. Favicon.ico is usually opened in the webview of your App. This favicon. ico is not loaded, but many pages can be shared.

If the user opens favicon.ico in the browser, the call will fail. Generally, try to ensure that the icon exists by default, keep the file as small as possible, and set a long cache expiration time. In addition, resources that fail to make existing requests due to cache expiration should be cleaned up in time.

8. Why is it more effective to use multiple domain names to store website resources?

  • CDNCaching is more convenient;
  • Breaking the browser concurrency limit;
  • savecookieBandwidth;
  • Save the connection number of the main domain name, optimize the page response speed;
  • Prevent unnecessary security problems.

9. Have a page that must present the latest data in real time. What are your solutions?

  • httpPolling, using Ajax with timer timing request data update;
  • websocketIs used to handle the long connection protocol pushed by the server.

πŸ’­ 4. Performance optimization article supplement

Detailed explanation of the article added πŸ‘‡

  • In terms of front-end performance optimization, we should understand the loading process of web pages and anti-shaking throttling
  • Links: juejin. Cn/post / 697306…

πŸ’―. Conclusion

As front-end projects grow and browser rendering becomes more and more stressful, many organizations have teams dedicated to performance optimization. For performance optimization of the interview questions, mainly to investigate whether candidates have a certain understanding of website performance optimization.

Therefore, how to do a good job in performance optimization, which operations will cause performance optimization problems, are worth paying attention to.

And that’s the end of the interview questions about performance optimization. Hope to help you ~

🐣 Egg One More Thing

🏷️ Resources

πŸ‘‰21 interview questions about performance optimization (with answers)

🏷️ PDF

πŸ‘‰ wechat public account Monday laboratory, click the navigation bar below the interview column briefly view the keyword to obtain ~

🏷 ️ set pieces

  • If this article is useful to you, be sure to leave a footprint
  • That’s all for this article! See you next time! πŸ‘‹ πŸ‘‹ πŸ‘‹