Front-end internship interview and project-related questions, a collection of reference: front-end small white interview question set

1. Optimization in the project?

Reference:Give you a picture, understand performance optimization, no longer afraid of the interviewer’s interrogation

1.1 Coding layer optimization

  • V-if and V-show are used in different scenarios:

V-if is not rendered if the initial value is false, v-show is rendered anyway, so v-if is good for situations where conditions rarely change, and v-show is good for scenes that change frequently;

  • Use scenarios for computed and Watch:

Computed: Computed attributes depend on other attribute values, and computed values are cached. Only when the dependent attribute values change, computed values will be recalculated the next time it obtains computed values.

Watch: It is more of a function of “observation”, similar to the listening callback of some data. Whenever the monitored data changes, the callback will be executed for subsequent operations.

When we need to do numerical calculations and rely on other data, we should use computed, because we can take advantage of the caching nature of computed and avoid recalculating each time we get a value.

Watch should be used when we need to perform asynchronous or expensive operations when data changes. Using the Watch option allows us to perform asynchronous operations (accessing an API), limits how often we perform that operation, and sets the intermediate state until we get the final result. These are all things you can’t do with computed properties.

  • V-for traversal must add a key to the item and avoid using v-if at the same time:

During the traversal rendering of list data, a unique key value should be set for each item to facilitate the accurate finding of the list data by vue.js internal mechanism. When state is updated, the new state value is compared to the old state value to locate the DIFF faster.

V-for has a higher priority than V-if, and if you need to traverse the entire array every time, it will affect speed, especially if you need to render a small part of it. Replace this with a computed attribute if necessary.

  • Long list performance optimization:

Vue hijacks data via Object.defineProperty to make the view respond to data changes. However, sometimes our component is purely a data presentation and nothing will change. We don’t need Vue to hijack our data. This significantly reduces component initialization time, so how do we prevent Vue from hijacking our data? Freeze can be used to freeze an Object. Once the Object is frozen, it cannot be modified.

  • Event destruction:

When a Vue component is destroyed, it automatically cleans up its connections to other instances and unties all its instructions and event listeners, but only for the component’s own events. If you use addEventListene or other methods in js, they will not be automatically destroyed. You need to manually remove the listener for these events when the component is destroyed to avoid memory leaks.

  • Lazy loading of pictures:

For pages with too many pictures, in order to accelerate the page loading speed, we often need to not load the pictures that do not appear in the visual area of the page, and then load them after scrolling to the visual area. This will greatly improve page loading performance and improve the user experience. We used Vue’s VUE-Lazyload plug-in in our project

  • Route lazy loading:

Vue is a single-page application, which may have a lot of routes introduced. In this way, the files packaged with WebPCAk are very large. When entering the home page, too many resources are loaded, and the page will appear white screen, which is not conducive to user experience. It would be much more efficient if we could split the components corresponding to different routes into different code blocks and then load the components only when the routes are accessed. This will greatly speed up the first screen, but may slow down the rest of the page.

const Foo = () => import('./Foo.vue')
const router = new VueRouter({
  routes: [
    { path: '/foo', component: Foo }
  ]
})
Copy the code
  • Third-party plug-ins are introduced on demand:

We often need to introduce third party plug-ins in a project. If we introduce the whole plug-in directly, it will cause the project to become too large. We can use babel-plugin-Component to reduce the size of the project by introducing only the required components. The following is an example of introducing an element-UI component library into a project:

//.babelrc
{
  "presets": [["es2015", { "modules": false }]],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

//main.js
import Vue from 'vue';
import { Button, Select } from 'element-ui';

 Vue.use(Button)
 Vue.use(Select)
Copy the code
  • Optimize infinite list performance:

If your application has very long or infinitely scrolling lists, you may need to use windowing techniques to optimize performance, rendering only a few areas of content, reducing the time to re-render components and create DOM nodes. You can optimize this infinite list scenario by referring to the following open source projects vue-virtual-Scroll list and vue-virtual-scroller.

  • Server render SSR or pre-render:

Server-side rendering refers to the process of Vue rendering the entire HTML fragment of the tag on the client side at the server side. The HTML fragment formed by the server side is directly returned to the client side. This process is called server-side rendering.

Advantages of server-side rendering:

Better SEO: Because the content of SPA page is obtained through Ajax, and the search engine crawl tool does not wait for the completion of Ajax asynchronism before grabbing the page content, so the content of SPA page obtained through Ajax cannot be captured; SSR is directly returned by the server to the rendered page (data has been included in the page), so the search engine crawler can grab the rendered page;

Faster content arrival time (faster loading on the first screen) : SPA will wait for all Vue compiled JS files to be downloaded before rendering the page. File download takes a certain amount of time, so rendering on the first screen takes a certain amount of time. SSR directly returns the page rendered by the server directly, without waiting to download JS files and render again, so SSR has a faster content arrival time;

Disadvantages of server-side rendering:

More development constraints: for example, server-side rendering only supports the beforCreate and Created hook functions, resulting in some external extension libraries requiring special handling to run in server-side rendering applications; And unlike fully static single-page application SPA, which can be deployed on any static file server, server-side rendering applications need to be in the Node.js server running environment;

More server load: Rendering a full application in Node.js is obviously more cpu-intensive than a server that just serves static files, so if you expect to use it in a high-traffic environment, prepare for the server load and use caching wisely.

If your project’s SEO and first screen rendering are key metrics for evaluating your project, then your project needs server rendering to help you achieve the best initial load performance and SEO. If your Vue project only needs to improve THE SEO of a few marketing pages (e.g. /, /about, /contact, etc.), Then you might need to pre-render and simply generate static HTML files for specific routes at build time. The advantage is that it’s easier to set up pre-rendering and you can treat your front end as a completely static site, which you can easily add using the prerender-spa-plugin.

1.2 Webpack layer optimization

  • Webpack compresses images:

In the vue project, except the limit size can be set in the url-loader of webpack.base.conf.js to process images, and the images smaller than the limit can be converted to base64 format, the rest of the operation is not done. Therefore, for some large image resources, the loading will be slow when the resource is requested. We can use image-webpack-loader to compress the image.

  • Reduce redundant code from ES6 to ES5:

The Babel plug-in will inject some helper functions when converting ES6 code to ES5 code:

Babel - the runtime/helpers/createClass / / used to implement the class grammar Babel - the runtime/helpers/inherits / / used to implement the extends the syntaxCopy the code

By default, Babel will embed these dependent helper functions in each output file, and if multiple source files rely on these helper functions, the code for these helper functions will appear many times, causing code redundancy. In order not to let the auxiliary function code is repeated, can rely on them through the require (‘ Babel – the runtime/helpers/createClass) way to import, so you can do to make them appear only once. The babel-plugin-transform-Runtime plugin does this by replacing the relevant helper functions with import statements to reduce the file size of the code compiled by Babel.

  • Extract common code:

If the third party libraries and common modules for each page are not extracted from the project, the project will have the following problems:

The same resources are loaded repeatedly, wasting user traffic and server costs.

Too many resources need to be loaded on each page. As a result, the first screen of a web page loads slowly, affecting user experience.

So we need to separate common code from multiple pages into separate files to optimize the above problem. Webpack has built-in plugin CommonsChunkPlugin which is specially used to extract the common parts of multiple chunks. The configuration of CommonsChunkPlugin in our project is as follows:

// All packages that depend on package.json are packaged into vendor.js. new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function(module, count) { return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, '.. /node_modules') ) === 0 ); }}), / / extract code module mapping new webpack.optimize.Com monsChunkPlugin ({name: 'the manifest, chunks: [' vendor']})Copy the code

It is worth noting that this plugin is Webpack4 abandoned, version 4 + using optimization. SplitChunks and optimization runtimeChunk instead.

  • Template precompilation:

When using a template in the DOM or a string template in JavaScript, the template is compiled into a rendering function at run time. This is usually fast enough, but it is best avoided in performance-sensitive applications. The easiest way to precompile a template is to use a single file component — the relevant build Settings take care of the precompilation automatically, so the built code already contains the compiled renderers instead of the original template strings. If you use Webpack and prefer to separate JavaScript and template files, you can use vue-template-loader, which also converts template files into JavaScript rendering functions during build.

  • Extraction of CSS:

When using a single-file component, the CSS within the component is dynamically injected through JavaScript in the form of a style tag. This has some small runtime overhead, and if you use server-side rendering, this will result in a “style-free content flicker” (FOUC). Extracting the CSS for all components into the same file avoids this problem and also allows CSS to be better compressed and cached. Consult the build tool’s documentation to learn more:

Webpack + Vue-loader (vue-CLI webpack template has been pre-configured)

Browserify + vueify

Rollup + rollup-plugin-vue

  • Optimize sourcemap

After the project is packaged, we will package multiple files and codes under development into one file. After compression, removing redundant Spaces and Babel compilation, the compiled code will be used in the online environment. Then the code after such processing will be very different from the source code. We can only locate the compressed code, not the code in the development environment. It is bad for development to tune the problem, hence sourceMap, which is designed to solve the problem.

Cheap -module-eval-source-map

Recommended production environment: cheap-module-source-map

Here’s why:

Cheap: The column information in the source code is of no use, so we do not want the packaged file to contain column-related information, only the row information to establish the dependencies before and after the package. Therefore, in both development and production environments, we want to add the base type cheap to ignore column information before and after packaging;

Module: In both development and formal environments, we want to locate the source code of the bug. For example, a Vue file reported an error. We want to locate the Vue file, so we also need the Module configuration.

Soure-map: Source-map generates a separate Soucemap file for each packaged module, so we need to add the source-map attribute;

Eval-source-map: Eval is very fast to package code because it does not generate a map file, but you can use eval-source-map on an EVAL combination to store the map file as a DataURL in a packaged JS file. Do not use eval-source-map in a formal environment because it increases the file size, but in a development environment, try it out because they pack quickly.

  • Analysis of construction Results

The code output from Webpack was very unreadable and the files were very large, which gave us a headache. In order to analyze the output more easily and intuitively, a number of visual analysis tools have emerged in the community. These tools graphically present the results more visually, allowing us to quickly understand the problem. Let’s move on to the analysis tool we used in the Vue project: Webpack-bundle-Analyzer.

1.3 Web-based Optimization

  • Enable Gzip compression

Gzip is the abbreviation of GNUzip. It was first used for file compression in UNIX systems. Gzip encoding over THE HTTP protocol is a technique used to improve the performance of Web applications, and both web servers and clients (browsers) must support GZIP. Chrome, Firefox and Internet Explorer all support this protocol. Common servers such as Apache, Nginx, IIS also support gzip compression efficiency is very high, usually can reach 70% compression rate, that is, if your web page has 30K, after compression becomes about 9K

  • Browser cache

In order to improve the speed of user loading pages, it is very necessary to cache static resources. According to the classification of whether to re-send requests to the server, HTTP cache rules are divided into two categories (mandatory cache, negotiated cache).

  • The use of CDN

When a browser downloads CSS, JS and images from a server, it has to connect to the server. Most servers have limited bandwidth. CDN can load files through different domain names, so that the number of concurrent connections to download files is greatly increased, and CDN has better availability, lower network delay and packet loss rate.

2. Does the team have any difficulty in cooperating? How did it work out

  • The front and back end, data processing separation, each to perform their own duties;
  • Version control;
  • Development documentation;

3. Basic operations of Git

  • Initialization:git-init
  • Add 1.txt file to buffer:git add .\1.txt

(git add.) (Add all files in current directory to buffer)

  • Commit:Git commit -m
  • Connection lot:git remote add origin http://....
  • View status:git status
  • View the current branch:git branch -v
  • Create and go to branch B1git checkout -b b1
  • Merge branches: after going to the Master branch,git merge b1
  • Roll back:git reset(– Mixed (Archive and buffer)/ Hard (Workspace Buffer and archive)/soft)) version number
  • All operations on all branches (including deleted commit records and reset operations) :git relog
  • View all submitted versions:git log
  • Create a new commit that goes back to some previous version, but does not affect subsequent commits:git revert
  • Synchronizing local data with remote data:git pull(This is actually a merge of two codes:git fetchView the remote versiongit merge origin/masterMerge remote trunk)
  • Synchronize the remote branch dev with the local dev:git push origin dev
  • Request merge:pull request(SSH can be used to generate a key for remote secret-free login.)

If the branch tries to merge something that conflicts with the trunk, it will fail and will be prompted to change it manually

  • git merge: Does not retain a commit for the branch of merge. Run the merge command to merge branches, resolve conflicts, and run the merge commandgit add .andgit commit -m'fix conflict'. A COMMIT is generated at this point.
  • git rebase: Run the rebase command to merge branches, resolve conflicts, and run the commandgit add .andgit rebase --continue, no additional commit will be made. The benefit of this is that, ‘clean’, there is no meaningless resolution on the branch commit; On the downside, if there are multiple Commits in the merged branch, multiple conflicts need to be handled repeatedly.
  • merge --no-ffForce-off the fast-forward mode so that each merge creates a new COMMIT recordgit mergeEven in the fast

The forward condition also produces a new onemerge commitTo avoid losing information. If you do not add –no-ff, all previous merges are erased and only a post-merge COMMIT remains.

4. What are the optimization methods for image loading?

Image related optimization:

  • No images: Use CSS instead of images.
  • Use vector maps instead of bitmaps: For most patterns, ICONS, etc., vector maps are smaller and scalable without generating multiple sets of maps.
  • Use the right image format: Don’t forget to use a good image encoder and the right parameters. Good image encoders, especially those with lossy image formats, can achieve higher compression ratios through algorithmic or manual adjustments.

General optimization:

  • Set a proper cache based on the HTTP protocol: Specific cache policies (such as permanent cache + rename) and deployment policies (such as reverse proxy and CDN) are not expanded here.
  • Use spdy-enabled servers: SPDY can be considered an early implementation of future HTTP 2.0, with Chrome, Firefox 13+, Opera 12+, and IE 11+ all supporting SPDY.
  • As we can no longer wait until all other resources are downloaded, we can no longer wait until the element is visible. At the moment it’s basically all scripted. In the future, HTML and CSS will add related control properties, see Resource Priorities.
  • Resource prefetch: available, see www.whatwg.org/specs/web-a… 9 performs DNS pre-resolution on the hostname of the resource. If you really need more control, use a script. Note: Chrome support is similar to Prefetch but further, and SPDY has added subResource Link support which is similar to Prefetch but has different semantics.
  • Use data URLS: Resources are embedded in CSS or HTML rather than having to be requested separately. Note that resources that need to be used in more than one place may not be suitable for this optimization method because the image data is duplicated, increasing traffic. In addition, many browsers have length restrictions on data urls, so be aware of the size of the resource.

5. Performance evaluation

Monitor the user’s FPS frame rate

  • Animations at 50-60 FPS will be smooth and comfortable;
  • Animation between 30 and 50 FPS, due to different sensitivity, comfort from person to person;
  • Animation at a frame rate of less than 30 FPS makes people feel sluggish and uncomfortable.