In view of the interview rate is relatively high difficult knowledge comb.

This is a series of articles:

Last:Ninety-nine percent tips for a front-end interview (1)

Fourth, modular development

4.1 What is a module

  • Encapsulate a complex program into several blocks (files) according to certain rules (specifications) and combine them together
  • The internal data and implementation of a block are private, exposing only interfaces (methods) to communicate with other external modules

4.2 Benefits of modularity

  • Avoiding naming conflicts (reducing namespace pollution)
  • Better separation, load on demand
  • Higher reusability
  • High maintainability

4.3 Modular Specifications

1, the CommonJS

Basic syntax:

  • Exposure module:module.exports = valueorexports.xxx = value
  • Introduction module:require(xxx)If the module is a third-party module, XXX is the module name. For a custom module, XXX is the module file path

Loading a module loads the module.exports property of that module. The require command is used to load module files. The basic function of the require command is to read and execute a JavaScript file and then return the exports object of that module. If no specified module is found, an error is reported. The loading mechanism for CommonJS modules is that the input is a copy of the output value. That is, once a value is printed, changes within the module do not affect that value. This is a major difference from ES6 modularity.

2. ES6 modular

The export command is used to specify the external interface of a module, and the import command is used to input functions provided by other modules.

Math.js **/ var basicNum = 0; var add = function (a, b) { return a + b; }; export { basicNum, add }; /** reference module **/ import {basicNum, add} from './math'; function test(ele) { ele.textContent = add(99 + basicNum); }Copy the code

You can also use export default

// export-default.js
export default function () {
  console.log('foo');
}

// import-default.js
import customName from './export-default';
customName(); // 'foo'
Copy the code

3. Differences between ES6 module and CommonJS module

There are two important differences:

  • The CommonJS module prints a copy of the value, the ES6 module prints a reference to the value.
  • The CommonJS module is run time loaded, and the ES6 module is compile time output interface.

Encapsulate the request and add a public header

Add the header

// Create an axios instance let instance = axios.create({timeout: 1000 * 12}); / / set the post request header instance. Defaults. Headers. Post [' the content-type '] = 'application/x - WWW - form - urlencoded'; instance.defaults.withCredentials=true; // Make Ajax carry cookiesCopy the code

Add the header to the API method

postJson(url, params) { return axios.post(`${base}${url}`, params, { headers: {'content-type': 'application/json; Return axios.get(' ${base}${url} ', {params: Post (url, params) {return axios.post(' ${base}${url} ', json.stringify (params))},Copy the code

Page performance optimization

Performance tuning is almost a must, and it’s best to mention the following five ways.

The second and third points extend, and the parentheses are the general directions of extension. See page performance for a detailed explanation

Objective: To speed up interface display and reduce the number of data requests.

What are some ways to improve page performance?

  1. Resource compression merges to reduce HTTP requests
  2. Asynchronous loading of non-core code (how to load asynchronously, the difference between asynchronous loading)
  3. Make use of browser caches (cache classification, cache principles)
  4. Use the CDN
  5. Preliminary analytical DNS
<meta http-equiv="x-dns-prefetch "content="on"> href="//host_name_to_prefetch.com">Copy the code

Browser cache

Classification of cache policies:

  • Strong cache
  • Negotiate the cache

Caching policies are implemented by setting HTTP headers. Each time the browser initiates a request, it first looks up the result of the request and the cache identifier in the browser cache. Each time the browser receives the result of the returned request, it stores the result and the cache id in the browser cache.

7.1 strong cache

Strong cache: Does not send a request to the server, but reads resources directly from the cache. In the Network option of the Chrome console, the request returns a status code of 200, and Size displays from Disk cache or from Memory cache. Strong caching can be implemented by setting two HTTP headers: Expires and cache-Control.

1. Expires

Cache expiration time, used to specify the expiration time of resources, is a specific point in time on the server. That is, Expires=max-age + request time needs to be used in combination with last-Modified. Expires is a Web server response header field that tells the browser in response to an HTTP request that the browser can cache data directly from the browser before the expiration date without having to request it again. Expires is a product of HTTP/1 and is limited to local time, which can invalidate a cache if you change it. Expires: Wed, 22 Oct 2018 08:41:00 GMT Indicates that the resource will expire after Wed, 22 Oct 2018 08:41:00 GMT and needs to be requested again.

2. Cache-Control

In HTTP/1.1, cache-control is the most important rule and is used to Control web page caching. For example, cache-control :max-age=300 means that the strong Cache will be hit if the resource is reloaded within 5 minutes of the correct return time of the request (which the browser records). Cache-control can be set in either the request header or the response header, and can be combined with multiple instructions:

3. Compare Expires and Cache-control

The difference is that Expires is a product of HTTP1.0 and cache-Control is a product of HTTP1.1. If both exist, cache-Control takes precedence over Expires. In some environments where HTTP1.1 is not supported, Expires can be useful. So Expires is an outmoded object that currently exists as a way to write compatibility. Strong caches Determine whether or not the cache is cached based on whether or not the server side file has been updated after a certain time or period, which may result in the loading file is not the latest content on the server side, so how do we know whether the server side content has been updated? Here we need to use a negotiated cache strategy.

7.2 Negotiated Cache

Negotiation cache is a process in which the browser sends a request to the server with the cache ID after the cache is invalid, and the server decides whether to use the cache based on the cache ID. There are two main situations:

  • The negotiated cache takes effect, returning 304 and Not Modified
  • Negotiation cache invalid, return 200 and request result

Negotiated caching can be implemented by setting two HTTP headers: Last-Modified and ETag.

1. The last-modified and If – Modified – Since

When the browser accesses the resource for the first time and the server returns the resource, the last-Modified header is added to the response header, whose value is the Last modification time of the resource on the server. The browser caches the file and header after receiving it.

Last-Modified: Fri, 22 Jul 2016 01:47:00 GMT
Copy the code

The next time the browser requests the resource, the browser detects a last-Modified header and adds if-modified-since, which is the last-modified value; When the server receives the resource request again, it compares the value in if-modified-since with the last modification time of the resource in the server. If there is no change, it returns 304 and an empty response body, reading directly from the cache. If the time of if-modified-since is less than the time of the last modification of the resource on the server, the file has been updated, and the new resource file and 200 are returned. But last-Modified has some drawbacks:

  • If the cache file is opened locally, last-Modified is Modified even if the file is not Modified. The server cannot match the cache and sends the same resource
  • Because last-Modified can only be measured in seconds, if the file is Modified in an imperceptible amount of time, the server will assume that the resource is still a hit and will not return the correct resource

Since the cache is not sufficient based on the file modification time, can the cache policy be determined directly based on the file content modification? ETag and if-none-match were introduced in HTTP / 1.1

2. The ETag and If – None – Match

An Etag is a unique identifier (generated by the server) that is returned to the current resource file when the server responds to a request. The Etag is regenerated whenever the resource changes. When the browser sends a request to the server next time it loads a resource, it will add the Etag value returned last time to if-none-match in the request header. The server only needs to compare the if-none-match value sent by the client with the Etag of the resource on the server. It is a good idea to determine whether the resource has been modified relative to the client. If the server finds that the ETag does not match, it sends the new resource (including the new ETag) to the client in a regular GET 200 packet return. If the ETag is consistent, 304 is returned to inform the client to use the local cache directly.

3. Compare the two

  • First, Etag is superior to Last-Modified in accuracy.

Last-modified time is measured in seconds. If a file changes several times within a second, their last-Modified version does not actually show up, but Etag changes each time to ensure accuracy. If the server is load-balanced, the last-Modified generated by each server may also be inconsistent.

  • Second, in terms of performance, Etag is inferior to Last-Modified, because last-Modified only takes time to record, whereas Etag requires the server to compute a hash value through an algorithm.
  • Third, server verification takes Etag as the priority

7.3 Cache Mechanism

The mandatory-cache takes precedence over the negotiated Cache. If mandatory-cache (Expires and cache-control) is valid, the Cache is used directly, and If not, the negotiated Cache (last-modified/if-modified-since and Etag/if-none-match) is used. The server decides whether to use the negotiated cache. If the negotiated cache is invalid, the cache of the request is invalid. 200 is returned, and the resource and cache id are returned again, and then stored in the browser cache. If it takes effect, return to 304 and continue to use the cache.

The difference between strong cache and negotiated cache can be expressed in the following table:

Cache type Form of resource acquisition Status code Send the request to the server
Strong cache From the slow access 200 (from cache) No, cache access directly
Negotiate the cache From the slow access 304 (Not Modified) If yes, the server tells you whether the cache is available

The impact of user behavior on caching

The user action Expires/Cache-Control Last-Modied/Etag
Address enter effective effective
Page link jump effective effective
A new window effective effective
Move back effective effective
F5 to refresh invalid effective
Ctrl+F5 Force refresh invalid invalid

7.4 Comparison between from Memory Cache and From Disk Cache

The size bar in Console Network in Chrome usually has three states

  1. from memory cache
  2. from disk cache
  3. The size of the resource itself (e.g. 1.5K)

Three differences:

  • From the memory cache: Literally from memory, also is the literal meaning, actually this is directly from the memory resources, general won’t request to the server has been loading the resource and cached in memory, when close the page, this resource to be released down to memory, once again back on the same page won’t appear the from the memory cache.
  • From Disk cache: The resource is fetched from the disk and has been loaded at a previous time. The server does not request the resource. However, the resource will not be released when the page is closed because it is stored in the disk and will still be from the disk cache next time
  • Resource size: When the HTTP status is 200, the resource is actually obtained from the browser. When the HTTP status is 304, the resource size is the size of the packet communicated with the server, not the size of the resource itself. The resource is obtained locally
state type instructions
200 form memory cache Do not request network resources, resources in memory, ordinary scripts, fonts, images will be stored in memory.
200 form disk ceche Do not request network resources. In disks, non-scripts are generally stored in memory, such as the CSS.
200 Resource size value Resource size value Downloads the latest resource from the server.
304 Packet size The requesting server finds that the resource is not updated and uses the local resource, that is, matches the negotiated cache.

8. Webpack basic configuration

Webpack is one of the most common questions to ask in an interview for advanced front-end development, and a little preparation is better than nothing

8.1 Basic Concepts

The default configuration file for Webpack is webpack.config.js.

Webpack can only handle JS files by default. If you want to handle other files such as images, you need to use the corresponding Loader. For example, file-loader, URl-loader, CSS-loader, and style-loader. If sass is used, sas-loader is used.

A few other important concepts are:

  • Mode: Specifies the packaging mode, development or production.
  • Devtool: Specifies how to generate sourceMap.
  • Entry: configures the entry file. If multiple files are packaged, several entries are written in the entry, and a placeholder is used for filename output[name]Said.
  • Output: the export.
  • Loader: Various tools to assist packaging.
  • Loaders are used to convert certain types of modules, while plugins can be used to perform a wider range of tasks. Such as HtmlWebpackPlugin, CleanWebpackPlugin.
  • DevServer: Use WebpackDevServer to enable hot update to improve development efficiency.

8.2 HMR thermal overload

Configuration method

const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const {CleanWebpackPlugin} = require('clean-webpack-plugin'); // Add this line const webpack = require('webpack'); module.exports = { mode: 'development', devtool: 'cheap-module-eval-source-map', entry: { main: './src/index.js', }, output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') }, devServer: {contentBase: './dist', open: true, port: 9090, // Add the following two lines hot: true, hotOnly: true}, plugins: [ new HtmlWebpackPlugin({ template: "SRC/index. The HTML"}), new CleanWebpackPlugin (), / / line to add this new webpack HotModuleReplacementPlugin ()], the module: {rules: [ { test: /\.(png|jpg|gif|jpeg)/, use: { loader: 'file-loader', options: { name: '[name]_[hash].[ext]', outputPath: 'images/' } } }, { test: /\.(eot|woff|svg|ttf)/, use: { loader: 'file-loader', } }, { test: /\.(css|scss)/, use: [ 'style-loader', { loader: 'css-loader', options: { importLoaders: 2, // modules: true } }, 'sass-loader', 'postcss-loader' ] } ] } }Copy the code

CSS hot reload style-loader and CSS-loader have been implemented for us.

JS thermal overload

// Check whether hot updates are enabled if (module.hot){// Listen for hotTest. Js files, Module.hot.accept ('./hotTest. Js ', () => {// hotTest(); })}Copy the code

8.3 Code and image compression

Compressed JavaScript

At present, the most mature JavaScript code compression tool is UglifyJS, which will analyze the syntax tree of JavaScript code and understand the meaning of the code, so as to achieve optimization such as removing invalid code, removing log output code, shortening variable names, etc.

To access UglifyJS in Webpack, you need to use plug-ins. Currently, there are two mature plug-ins, which are as follows:

  • UglifyJsPlugin: Compression by encapsulating UglifyJS.
  • ParallelUglifyPlugin: Parallel compression for multiple processes.

The compressed image

Compress images using image-webpack-loader

Enable Gzip compression

Enabling gzip also significantly compresses the size.

Okay, so that’s it for today, and more in the next video.

The last

Entering big factory is not so difficult as imagined, the key is technology.

Opportunities are left to prepared people, understand the job requirements, early preparation, do enough preparation, you can take detdetments, online all kinds of surface by pen, learning courses.

The following share with you a “front-end development engineer essential information pack” I organized.

269 pages of the front-end factory interview treasure book

Front end test summary

JavaScript

performance

linux

jQurey

Applet correlation

Front-end data summary

Due to the lack of space, a complete version ofEssential data pack for front-end development engineers“Friends directlyClick here to get it for free, I wish you a smooth wind and smooth water god of wealth!

conclusion

No matter what you do, you should have your own ideas and thinking, so that you can do things well and do them deeper. Otherwise this is like a dream, wake up or very moved. Hope you readers, look at the above topic is not back the answer, but to understand it, and can be used, do similar things in the future, there is a reference train of thought. If I meet with the same interviewer, of course, the topic is not exactly the same, at this time need to play their own accumulation and flexible use.

Finally, if you have seen the universal situation and understood the universal phenomenon, then if everything is the same as others, won’t it finally become the universal level? If you want to break away from the current status quo and achieve a breakthrough, then the goal should be to become a person with personality, characteristics and distinction, to become a different front end, a different person.