HTML5:

1. How do you understand HTML semantics? (study)

  1. At the beginning of the chaotic stage: write the HTML table tag layout in the background
  2. Art stage: DIV+CSS layout but not semantic enough
  3. Front end: Use h1 P article and other tags professional

2. What does meta Viewport do?

Example: The Meta ViewPort is designed for mobile devices, so that pages of any width can be perfectly adapted on mobile devices (no need for users to zoom and scroll horizontal scrollbars, fonts, images, etc.).

<meta name="viewport" content="width=device-width, initial-scale=1,
maximum-scale=1, minimum-scale=1,user-scalable=no">
Copy the code

Then explain the meaning of each word one by one: device width, initial ratio, maximum ratio, minimum ratio


3. Common HTML5 tags

Content related: Header main Footer Aticle Function related: Canvas Video Oudio

How does a canvas draw?

var canvas = document.getElementById('canvas') var ctx = canvas.getContext('2d') ctx.fillstyle = 'green'; CTX. FillRect (10,10,100,100)Copy the code

First get a Canvas, then get the 2D (2d) context of this canvas, then set the canvas brush color, and set the brush range. Video So what attributes do you add to videodisc? SRC is the address of the video,autoPlay is the address of the video,poster is the cover of the video, and you can use track to add subtitles. Compatibility: Chrome: 3.0 Firefox: 3.5 Internet Explorer: 9.0


4. What is H5?

H5 stands for mobile page. All kinds of pages on mobile phone that can be opened by browser can be called H5 in general. H5 is mainly applied in electronic invitation letter, electronic brochure, enterprise report slides, information collection, etc. H5 is a product term, while HTML5 is a technology term.


CSS:

1. Two box models of CSS (required test)

1, content-box: width = content border-box: Summary: After defining the width of the content box model, the padding and border will change the actual size of the box. If you want to keep the size fixed, you need to calculate it. After defining the width of the border box model, the padding and border widths are fixed to the width at which they are written. However, content may be compressed, resulting in abnormal layout. Why is there a new box model? Ask which of the two box models is good? The margin and border of the traditional box model will support the big box, which will bring us a lot of difficulties in practical development. For example, we have arranged many modules by floating or positioning, but now we only need a larger space between each module. If we use the border or padding of the traditional box model, the layout we set up before will be destroyed. This is why border-box is better.


2. Required test: How to achieve vertical center?

Discussion by case (seven ways to achieve vertical center)

If the height of the. Parent is not dead, just use the padding: 10px 0; You can center.child vertically; If the height of.parent is dead, it’s hard to center.child. Here’s how to center.child vertically. Tip: Never write height if you can’t.

1. Table has built-in functions:

<table class="parent"> <tr> <td Class = "child" > a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string of words a string of words a string of words a string of words a string of text a string of words a string of words a string of words a string of words a bunch of text text a string of a string of a string of text </td> </tr> </table> CSS:.parent{border: 1px solid red; height: 600px; } .child{ border: 1px solid green; }Copy the code

2, 100% height before after plus inline-block

<div class="parent"> <span class=before></span><div class="child"> A string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string of a string of text text </div> <span class=after></span> </div> CSS:.parent{border: 3px solid red; hetght: 600px; text-align: center; } .child{ border: 3px solid black; display: inline-block; width: 300px; vertical-align: middle; } .parent .before{ outline: 3px solid red; display: inline-block; height: 100%; vertical-align: middle; } .parent .after{ outline: 3px solid red; display: inline-block; height: 100%; vertical-align: middle; }Copy the code

Optimized version:

<div class="parent"> <div class="child"> A string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string of a string of text text </div> </div> CSS:.parent{border: 3px solid red; hetght: 600px; text-align: center; } .child{ border: 3px solid black; display: inline-block; width: 300px; vertical-align: middle; } .parent:before{ content: ''; outline: 3px solid red; display: inline-block; height: 100%; vertical-align: middle; } .parent:after{ content: ''; outline: 3px solid red; display: inline-block; height: 100%; vertical-align: middle; }Copy the code

Div disguised as table

<div class="table"> <div class="td"> <div Class = "child" > a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string of words a string of words a string of words a string of words a string of text a string of words a string of words a string of words a string of words a bunch of text text a string of a string of a string of text </div> </div> </div> CSS: div.table{display: table; border: 1px solid red; height: 600px; } div.tr{ display: table-row; border: 1px solid green; } div.td{ display: table-cell; border: 1px solid blue; vertical-align: middle; } .child{ border: 10px solid black; }Copy the code

4, margin – top – 50%

<div class="parent"> <div class="child"> A string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string of a string of text text </div> </div> CSS:.parent{height: 600px; border: 1px solid red; position: relative; } .child{ border: 1px solid green; position: absolute; width: 300px; height: 100px; top: 50%; left: 50%; margin-left: -150px; margin-top: -50px; }Copy the code

5, translate – 50%

<div class="parent"> <div Class = "child" > a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string of words a string of words a string of words a string of words a string of text a string of words a string of words a string of words a string of words a bunch of text text a string of a string of a string of text </div> </div> CSS:. Parent {height: 600px; border: 1px solid red; position: relative; } .child{ border: 1px solid green; positon: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }Copy the code

6. Absolute Margin Auto

<div class="parent"> <div Class = "child" > a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string of words a string of words a string of words a string of words a string of text a string of words a string of words a string of words a string of words a bunch of text text a string of a string of a string of text </div> </div> CSS:. Parent {height: 600px; border: 1px solid red; position: relative; } .child{ border: 1px solid green; position: absolute; width: 300px; height: 200px; margin: auto; top: 0; bottom: 0; left: 0; right: 0; }Copy the code

Flex layout

<div class="parent"> <div Class = "child" > a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string a string of text text a string of words a string of words a string of words a string of words a string of words a string of words a string of words a string of words a string of text a string of words a string of words a string of words a string of words a bunch of text text a string of a string of a string of text </div> </div> CSS:. Parent {height: 600px; border: 3px solid red; display: flex; justify-content: center; align-items: center; } .child{ border: 3px solid green; width: 300px; }Copy the code

Heightening: Why is horizontal centring easier to achieve than vertical centring? Backtracking mechanism involving CSS rendering


3. How to use Flex and what are the common attributes? (study)

1. Enable flex layout

Just say display: flex on the parent element; For inline elements, write display: inline-flex; Display: -webkit-flex; display: -webkit-flex;

2. Properties on the parent container

A container has the following characteristics: The parent container can set the arrangement mode of its children, and the children can also set their own arrangement mode. If both Settings are set at the same time, the Settings of the child containers prevail. Flex -direction row: the default value. The axis is horizontal from left to right. Row-reverse: the main axis is horizontal from right to left; Column: spindle is vertical from top to bottom; Column-reverse: the main axis is vertical from bottom to top

Justify -content: flex-start, flex-end, center: space-between, space-around

Align-items: flex-start, flex-end, center Baseline: baseline stretch: stretch Line wrap: flex-wrap No line wrap: nowrap Line wrap: flex-start Wrap: wrap-reverse

Flex -flow refers to the direction in which the child flows and whether line breaks are allowed to flow to the end. For example, flex-flow: Row wrap, flex-flow is a compound attribute, equivalent to a combination of flex-direction and flex-wrap. The value can be: 1, row, column, etc., can be set up separate major axis 2, wrap, nowrap etc., can be separately set the wrap mode 3, row nowrap, column wrap, etc., can also be both set multiple lines along the cross axis alignment: Align-content Sets the alignment between lines when multiple lines are aligned in a child container. Position arrangement: flex-start, flex-end, center distribution arrangement: space-between, space-around stretch arrangement: stretch

3. Attributes on child containers

How to scale on the main axis: Flex child containers are elastic (flex is elastic), they automatically fill the remaining space, and the scale of the child container is determined by the Flex property. Align-self align-position: flex-start, flex-end, center Stretch Each child container can also define separately how to arrange along the cross axis. The optional value of this property is exactly the same as the parent align-items property. If both are set at the same time, the align-self property of the child container will be used. Set expansion scale: Flex-grow child container elastic stretch ratio. Set the shrink ratio: Flex-shrink Indicates the elastic shrink ratio of a child container. Set the order: order changes the order of the child containers, overwriting the order in the HTML code. The default value is 0, and the value can be negative, the smaller the value, the higher the order.


4. What is BFC? Give an example of when a BFC occurs. (study)

A BFC is called a Block Fromatting Context, and is part of a visual CSS rendering of a Web page. It is the area where block-level box layouts occur and where floating layer elements interact. Simply put, it is an attribute that affects the position and spacing between elements. Refers to a separate render area or an isolated container. If you give a div, say overflow: hidden; The floating elements inside the div will be wrapped around it.

Elements with BFC characteristics can be viewed as separate containers, the elements inside the container do not affect the layout of the elements outside, and BFC has some characteristics that normal containers do not have. In layman’s terms, the BFC can be thought of as a large, closed box, where the elements inside the box, no matter how turbulent, do not affect the outside. BFC has the following features: 1. The internal elements will be placed one after another in the vertical direction, starting from the top. 2. The vertical distance of the element is determined by margin. Margins of two adjacent elements belonging to the same BFC will be superimposed. 3. They all start on the far left. The left side of the margin box for each element, and the left side of the border box containing the block (for left-to-right formatting, otherwise the opposite). This is true even if there is a float. 4.BFC areas do not stack with float boxes. 5. A BFC is a separate container on a page, in which child elements do not affect outside elements and vice versa. 6. When calculating the height of the BFC, floating elements are also involved in the calculation (when there is a float inside the BFC, in order not to affect the layout of external elements, the BFC calculates the height of the floating element).

BFC usage scenarios: 1, solve the margin merge 2, clear floating principle 3, layout

By placing two elements with overlapping margins in different BFC containers, you create block-level formatting contexts: (Interviewers usually only know the following 🙂 1. Float element (float of element left or right except none) 3. Absolute position element (element position is absolute or fixed) 4. Inline block element 5.overflow block element 6 with values other than visible (hidden,auto, Scroll). Elastic elements (display is a direct child of flex or inline-flex elements)

The block formatting context contains everything inside the element that created it. The block formatting context is important for both locating floats (see float) and clearing floats (see clear). Float positioning and float clearing are only applied to elements in the same BFC. Floats do not affect the layout of elements in other BFC, and clearing floats only clears floats of elements before it in the same BFC. Margin collapsing also occurs only between block-level elements that belong to the same BFC. Margin merging margin merging refers to margin merging. MDN defines margin merging as follows: The top margin and bottom margin of a block are sometimes combined (folded) into a single margin, the size of which is the largest margin combined into it. This behavior is called margin merging. Note that margin merges are for block-level elements only, and are for top or bottom margins.

2. The parent element adds overflow:hidden to the parent element, creating a BFC(block format context) for the parent element.


5. Clear the float

.clearfix:after{ content: ''; Display: block /* or table*/; clear: both; } .clearfix{ zoom: 1; /* IE compatible */}Copy the code

.clearfix is added to the container, and the float of the child element inside is cleared


6. CSS selector priority

Common tag 0001 class: 0010 ID: 0100 Common tag 0001 class: 0010 ID: 0100 How does the browser find elements for descendant selectors? Browser CSS matches are not found from left to right, but from right to left. DIV#divBox p span. Red {color:red; }, the browser looks for all the span elements in the HTML class=’red’, then looks for p elements in the parent elements, and then checks whether the parent elements of P elements have div elements with id = divBox, if both exist, then matches. The advantage of browsers searching from right to left is to filter out extraneous style rules and elements early.

Not (.xxx):first-child{} is not(.xxx):first-child{} is not(.xxx):first-child{} is not(.xxx):first-child{} is not(.xxx):first-child{} Important is the highest priority, but use it sparingly


JavaScript

1. What do you know about ES 6 grammar? (study)

Let const arrow function Promise expand operator default parameter import export new ES 6 feature list: fangyinghang.com/es-6-tutori… Or see Ruan Yifeng getting started with ECMAScript 6: es6.ruanyifeng.com/


2. Promise, Promise. All, Promise. (study)

  1. Memorize the code Promise usage
Function fn(){return new Promise((resolve, reject)=>{resolve(reject, reject)})} fn().then(success, reject) fail).then(success2, fail2)Copy the code
  1. Memorize the code promise.all usage
Promise.all([promise1, promise2]). Then (Success1, fail1) Success1 is invoked when both promisE1 and faile2 succeedCopy the code

For example: The promise.all (iterable) method returns an instance of a promise, This instance is resolved when all promises in iterable arguments are “resolved” or resolve when no promises are included in the arguments; If the promise parameter has a failed (Rejected), this instance calls back failed (Reject), which is the result of the first failed promise. It is typically used after starting multiple asynchronous tasks to run concurrently and creating promises for their results so that one can wait for all tasks to complete. The iterable argument represents an iterable, such as Array or String. Example: Use of promise.all, promise.all waits for everything to complete (or the first failure).

var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
}); 
Promise.all([p1, p2, p3]).then(values => { 
  console.log(values); // [3, 1337, "foo"] 
});
Copy the code
  1. Memorize the code promise.race
Promise.race([promise1, promise2]). Then (Success1, fail1) If either promisE1 or promisE2 fails, fail1 is invoked.Copy the code

In short, whoever succeeds or fails first is considered the success or failure of race. Promise.race is used to handle multiple requests, using the fastest (whichever completes first). The promise.race (iterable) method returns a Promise that is resolved or rejected once a Promise in the iterator is resolved or rejected.

const promise1 = new Promise((resolve,reject) =>{
   setTimeout(resolve,500,'one');
});
const promise2 = new Promise ((resolve,reject) => {
   setTimeout(resolve,100,'two');
});
Promise.race([promise1,promise2]).then((value) => {
  console.log(value);
  // Both resolve,but promise2 is faster
})  //expected output:"two"
Copy the code

3. Handwriting function tremble and function throttling

The function throttle can be understood as the CD cooldown time, which can be used to determine whether the scroll has reached the end at intervals when you pull the scroll bar.

function fn(){}
var cd = false
button.onclick = function(){
   if(cd){
      //
   }else {
      fn()
      cd = true
      var timerId = setTemeout(()=>{
	  cd = false
      },3000)
   }
}
Copy the code

Or:

// throttling (after executing once, Function throttle(fn, delay){let canUse = true return function(){if(canUse){fn.apply(this, arguments) canUse = false setTimeout(()=>canUse = true, delay) } } } const throttled = throttle(()=>console.log('hi')) throttled() throttled()Copy the code

The debounce function, which is used to perform tasks that are triggered too frequently (such as taking a takeaway order), will only execute if the interval between tasks triggers exceeds the specified interval. The callback is executed n seconds after the event is triggered, and if it is triggered again within n seconds, the timer is reset. Available in user name registration check: Checks whether the user name entered in the input box exists or is valid within a certain period of time.

  var timerId = null
  button.onclick = function(){
     if(timerId){
        window.clearTimeout(timerId)
     }
     timerId = setTimeout(()=>{
	 fn()
	 timerId = null
     },5000)
  }
Copy the code

Or:

// Buffeting (wait for a while, After this period of time, it will be carried with it. delay){ let timerId = null return function(){ const context = this if(timerId){window.clearTimeout(timerId)} timerId = setTimeout(()=>{ fn.apply(context, arguments) timerId = null },delay) } } const debounced = debounce(()=>console.log('hi')) debounced() debounced()Copy the code

4. The handwritten Ajax

var request = new XMLHttpRequest() request.open('GET','/a/b/c? Name = ff ', true) request. The onreadystatechange = function () {if {(request. ReadyState = = = 4). The console log (' request is completed) If (request.status >=200 && request.status <300){console.log(' request succeeded ') // console.log(request.responseText)}else{}}} request.send()Copy the code

Simplified version:

Var request = new XMLHttpRequest() request.open('GET','/ XXXX ') request.onload = ()=>{console.log(' request succeeded ')} request.send()Copy the code

What is AJAX? AJAX (adac-javascript -and XML) refers to Asynchronous communication of JavaScript to extract data from an XML document from a server and update the corresponding portion of the current web page without refreshing the entire web page. Later, the term AJAX became synonymous with HTTP communication initiated by JavaScript scripts, meaning that any communication initiated by a script could be called AJAX communication. AJAX steps: 1. Create XMLHttpRequest instance object 2. Make an Http request 3. The server returns a string in XML format 4.JS parses the XML and updates the partial page but as history has progressed XML has been phased out in favor of JSON.

JSON (JavaScript Object Notation) is a lightweight data interchange language conceived and designed by Douglas Crockford. It is a subset of JavaScript, so JSON retains many of the features of JavaScript syntactically. JSON does not have function, undefined, or NaN or Infinity in Number. JSON strings must start and end in double quotes, which means that the object’s keys must also be quoted; JSON is only a data format, and data format is actually a specification. Format, form, and specification cannot be used to store data. So things like var obj={“width”:100,”height”:200,”name”:”rose”} are not JSON objects, but JS objects in JSON format. The XMLHttpRequest object is the primary interface of AJAX for communication between the browser and the server. Despite XML and HTTP in its name, it can actually use multiple protocols (such as File or FTP) to send data in any format (both string and binary). Note: AJAX can only make HTTP requests to same-origin urls (same protocol, domain name, and port). If you make cross-domain requests, an error will be reported. XMLHttpRequest instance attributes of XMLHttpRequest. ReadyState XMLHttpRequest. The readyState property returns an XMLHttpRequest agent’s current state.


5. What is this in this code?

The call

1. fn() this => window 2. obj.fn() this => obj 3. fn.call(xx,yy) this => xx 4. fn.apply(xx) this=> xx 5. fn.bind(xx) This => xx 6.new Fn() this => new object 7.fn = ()=> {} this => outside this 8.with /this?Copy the code
  1. This is the first argument you pass in when you call a function. (Fixed formula “This is the first argument to call”)

2. If your function call is not a Call, follow the “Conversion code” to convert it to a Call. 3. Arrow functions do not have this in them. If you see this inside the arrow function, just think of it as this outside the arrow function.

Whatever this is outside, this is inside the arrow function, because the arrow function itself does not support this. Article: party should hang “what exactly is this value? A clear” zhuanlan.zhihu.com/p/23804247 authenticity array: such as a lot of people don’t know what a pseudo array, is simple: 1. An Array is true if its __proto__ refers directly or indirectly to array. prototye (using the Array’s common property). 2. An Array is a pseudo-array if its __proto__ does not refer directly or indirectly to array. prototye.

var realArr = {0: 'a', 1:'b', length: 2} realArr.__proto__ = array. prototype // This is true Array (not exactly) // equivalent to realArr = ['a', 'b'] realarr.push! Var fakeArr = {0: 'a', 1:'b', length: 2} realarr. push === undefined // trueCopy the code

6. What are closures/immediate functions?

Please brief me in your own words

  1. What is a “closure”?
  2. What do closures do?

Let’s begin by outlining what closures are:

Var local = 'variable' function foo(){console.log(local)}Copy the code

Local variables accessible inside function foo Suppose the above three lines of code are in an immediate function. In the three lines of code, there is a local variable local, and there is a function foo, which has access to external local variables.

Ok, so that’s a closure: the sum of the “function” and the “variables accessible within the function” (also known as the environment) is a closure. It’s that simple. Some students are confused, closure is so simple? “I’ve heard closures require a function to cover a function and return a function.” Like this:

function foo(){
  var local = 1
  function bar(){
    local++
    return local
  }
  return bar
}

var func = foo()
func()
Copy the code

The local variable and the bar function make up a Closure. Why do functions cover functions?

We put local in a function because we need local variables. If we don’t put local in a function, local is a global variable, failing the purpose of using closures to hide variables.

That’s why it says “run in an immediate function.” Some people see the name “closure” and think it has to be wrapped in something. This is a translation issue. The Closure is a Closure and has nothing to do with the “package”. So the function covers the function just to make a local variable, independent of the closure.

Why return bar? Because if you don’t return, you can’t use this closure. The same applies to return bar as window.bar = bar, as long as the bar function is accessible from outside. So the return bar is only for the bar to be used, and has nothing to do with closures. What closures do: Closures are often used to [indirectly access a variable]. In other words,[hide a variable]. Let’s say we’re making a game, and we’re writing code about how many lives we have left. Instead of closures, you could just use a global variable: window.lives = 30 // And thirty lives. What if I accidentally change this value to negative 1? So we can’t give someone “direct access” to this variable. What to do?

Use local variables. But with local variables others can not access, how to do? Expose an accessor (function) that others can “indirectly access.” The code is as follows:

! function(){ var lives = 50 window. = function(){lives += 1} window. Function (){lives -= 1}}()Copy the code

Then in other JS files, you can use window. reward a life () to increase the life, use Window. Kill a life () to kill a character.

Rumor about closures closures causing memory leaks? Fault. Whoever said that has no idea what a memory leak is. A memory leak is when a variable that you don’t need (or can’t access) still occupies memory space and can’t be reused. The variable inside the closure is clearly the variable we need (lives), why is it a memory leak? How did this rumor originate? Because Internet explorer. There is a bug in IE, IE is still unable to retrieve variables referenced in closures after we use them. This is an IE problem, not a closure problem. See The article by Masumi Seto.

Execute the function immediately

  1. Declare an anonymous function
  2. Call this anonymous function immediately

(function(){alert(‘ I’m an anonymous function ‘)}) () the above is a typical immediate function. Function (){alert(‘ I’m an anonymous function ‘)} The anonymous function is then called with a pair of parentheses () following it.

So why wrap another pair of parentheses around anonymous functions? In fact, it is compatible with JS syntax. If we write function(){alert(‘ I’m an anonymous function ‘)}() without another pair of parentheses, the browser will report a syntax error. To get past the browser’s syntax check, you need to add a few things, such as the following

(function () {alert (‘ I’m anonymous functions’)} (), / / the whole expression in brackets (function () {alert (‘ I’m anonymous functions’)}) () / / brackets wrapped function! Function (){alert(‘ I am an anonymous function ‘)}() {function(){alert(‘ I am an anonymous function ‘)}(); + function () {alert (‘ I’m anonymous functions’)} () function () {alert (‘ I’m anonymous functions’)} () to the function () {alert (‘ I’m anonymous functions’)} (void) The function () {alert (‘ I’m anonymous functions’)} () new function () {alert (‘ I’m anonymous functions’)} (2). What is the use of executing the function immediately? There is only one effect: create a separate scope. Variables in this scope cannot be accessed from outside (that is, to avoid “variable contamination”).

Take a famous interview question:

var liList = ul.getElementsByTagName('li') for(var i=0; i<6; I ++){liList[I]. Onclick = function(){alert(I)}}Copy the code

So why is alert always 6, because I goes through the scope, instead of assigning an I to each li so how do you solve this problem? Create a separate scope for each li with an instant-execute function (there are other ways, of course) :

var liList = ul.getElementsByTagName('li') for(var i=0; i<6; i++){ ! Function (1, 1, 2, 3, 4, 5){function(2, 1, 2, 3, 4, 5)}}(1, 1)}Copy the code

When the function is executed immediately, the value of I is assigned to ii, and the value of II remains unchanged thereafter. A change in the value of I from 0 to 5 corresponds to the six immediate functions in which ii is 0, 1, 2, 3, 4, and 5. That is the basic concept of executing functions immediately.


7. What is JSONP, what is CORS, and what is cross-domain? (study)

1. What is same-origin? A same-origin-policy is a convention.

It is the core and most basic security function of the browser. If the same origin policy is missing, the normal functions of the browser may be affected. The same origin policy is a famous security policy proposed by Netscape. This strategy is now used by all browsers that support JavaScript. Same name means same domain name, same protocol, same port. A non-same-origin client script cannot read or write other resources without explicit authorization. When requesting data, the browser raises an exception in the console, indicating that access is denied. Non-homogenous restrictions: Cookies cannot read dom cannot get Ajax requests cannot be sent

2. What is cross-domain

Cross-domain access refers to cross-domain access. The following cases are cross-domain access: Different domain name www.jd.com and www.taobao.com have the same domain name, Different ports www.jd.com:8080 and www.jd.com:8081 Different secondary domain names Item.jd.com and miaosha.jd.com If the domain name and port number are the same but the request path is different, the domain name does not belong to the cross-domain, for example: www.jd.com/item www.jd.com/goods Cross-domain problem is a security limitation of the browser for Ajax requests: Ajax requests initiated by a page can only be in the path of the same domain name as the current page, which can effectively prevent cross-site attacks. Therefore, cross-domain issues are a limitation against Ajax.

3. The json across domains

JSONP is short for jSON-with-padding. JSONP dynamically creates a script tag, using the SRC attribute of the script tag to retrieve javascript scripts in any domain. The js code of a function, called in SRC, is cross-domain. In order to facilitate the use of data by clients, an informal transfer protocol was gradually developed, which was called JSONP. One of the key points of the protocol was to allow the user to pass a callback parameter to the server, which then wrapped the JSONP data as a function name when the server returned the data. The client can then customize its own functions to automatically process the returned data. Due to the same origin policy, XMLHttpRequest only allows requests for resources from the current source (domain name, protocol, port). Instead of adding a

4. CORS across domains

CORS: Cross Origin Resource Sharing. CORS requires the support of both the browser and the server to achieve cross-domain requests. At present, almost all browsers support CORS, and Internet Explorer cannot be lower than Internet Explorer 10. The entire process of CORS is done automatically by the browser, without any front-end Settings, just like normal Ajax requests. Therefore, the key to achieve CORS lies in the server. As long as the server implements CORS interface, cross-domain communication can be realized. It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source. For simple requests, the browser sends the CORS request directly, specifically by adding the Origin request header field to the header. Also, in the response header, the relevant CORS header field set by the server is returned, with the Access-Control-Allow-Origin field as the source to Allow cross-domain requests. When a request is made, the browser describes the source of the request in Origin in the request header. After receiving the request, the server returns the request successfully.

Simple request: (1) The request method is one of the following: HEAD, GET, and POST (2) The HTTP header does not exceed the following fields: Accept, Accept-language, Content-language, and last-event-ID

Content-type: Application/X-www-form-urlencoded, multipart/form-data, Text /plain When the browser discovers that an Ajax request is simple, it will carry a field in the request header: application/ X-www-form-urlencoded, multipart/form-data, Text /plain Origin indicates which domain (protocol + domain + port) the current request belongs to. Based on this value, the server decides whether to allow it to cross domains. If the server allows cross-domains, you need to return the following information in the response header: Access-Control-allow-origin: Indicates an acceptable domain. It is a specific domain name or *, which stands for any domain. The advantages and disadvantages of CORS and JSONP are complementary:

  1. The main advantage of JSONP is better browser support; Although CORS is currently supported by major browsers, IT is not supported under IE10.
  2. JSONP can only be used to GET resources (that is, read-only, similar to GET requests); CORS supports all types of HTTP requests with complete functionality. (JSONP is exhausted at this point, but for the most part GET will suffice)
  3. JSONP error handling mechanism is not perfect, we can not do error handling; CORS can listen for errors through the onError event, and the browser console will see the error message, easy to troubleshoot.
  4. JSONP will only send a request once; For complex requests, CORS sends two requests.
  5. Always feel that security is a relative thing, there is no absolute security, also can not do absolute security. After all, JSONP is not a cross-domain specification, and it has obvious security issues: callback parameter injection and resource access authorization Settings. CORS at least is a cross-domain specification, in the resource Access authorization (access-Control-allow-Origin) restrictions, and standard browsers have made security restrictions, such as refusing to manually set the Origin field, is relatively safer.

But looking back, even if JSONP is not secure, we can still do some permissions on the server side, and both the server and client can still do some injection security, even if it is breached, it can only read some things. Even the more secure CORS can also be attacked when the server Settings are compromised or not in the cross-domain environment of the browser, and it can not only read, but also write.


How to use async/await? How to catch exceptions?

Async functions are syntactic sugar for Generator functions. Async is represented with the keyword async and await is used inside the function. The function returns a Promise object. If there is a return value in the function, encapsulate it as a Promise object with promise.resolve (). Async can only be used with and await. If used alone, an error will be reported. Ex. :

async function foo(){
  let bar = await test()
}
Copy the code

Await receives a Promise object after await. Await expression suspends execution of the current async function until the Promise processing completes. If the Promise is fulfilled normally, the resolve function parameter of its callback will be the value of the await expression and the async function will continue to be executed. If a Promise handles an exception (Rejected), the await expression throws the Promise’s exception reason. Also, if the value of the expression after the await operator is not a Promise, the value itself is returned. The value returned by the async function’s return becomes an argument to the then method’s callback. The state of the Promise returned by async functions will not change until all the Promise objects of the internal await command have been executed. That is, the callback to the then method is executed only when all asynchronous operations inside an async function have been executed. Normally, the await command is followed by a Promise, and if it is not, it will be converted to an immediately resolve Promise. Error handling: If an asynchronous operation following await fails, the Promise object returned by the async function is rejected. The way to prevent an error is we put it in a try/catch block, and catching an exception is a try catch.

async function fn(){
    try{
        let a = await Promise.reject('error')
    }catch(error){
        console.log(error)
    }
}
fn()
Copy the code

Promise method: Although the Promise method resolves callback hell, it fills Promise’s then() method, and if the processing process is complex, the entire code will fill then. The semantics are not obvious and the code flow does not represent the execution flow well. Generator mode: Generator mode solves some problems of Promise, and the process is more intuitive and semantic. The problem with Generator, however, is that function execution depends on the executor and needs to be g.ext () each time. Async mode: Async functions perfectly solve the problems of the above two modes. The process is clear, intuitive and semantic. Working with asynchronous processes is like working with synchronous processes. At the same time async function has its own executor, no need to manually load during execution.

Ruan Yifeng ES6 introduction: es6.ruanyifeng.com/?search=asy…


9. How to implement deep copy?

Code and keywords: 1. Recursion 2. Judgment type different types have different copy methods 3. Check for circular references (rings). If an object refers to itself, it may not get out during recursion. Check 4. __Proto__ cannot be copied. Copying a prototype is a shallow copy that wastes a lot of memory: an object in memory is copied to create a new space in memory. If the attribute of the object is the basic data type, then the value itself is copied. If the data type is complex, the copy copies the address. Therefore, modifying the new object will affect the original object. Object. The assign and {… Obj} are shallow copies. Deep copy: To create a new space and make a complete copy of the object, including the complex data type, without any relation to the original object. Create a new object. 2. Iterate over object 3 to be cloned. Add the corresponding member to the new object

 function qianClone(obj){
    var newObj={};
    for (var key in obj){
       newObj[key]=obj[key]
    }
     return newObj;
 }
 var xm={
    name:"xm",
    age:30,
    cars:{
      bmw:"30w",
      bench:"60w"
    }
 }
 var newXm=qianClone(xm);
 console.log(newXm)
Copy the code

Copy function is obviously implemented. What if you modify the copied object?

 newXm.name="Dm";
 newXm.cars.bmw="40w";
 console.log(newXm)
Copy the code

If you print the XM object, the CARS property of the XM object is also changed. So we can think of how to make a deep copy, the object inside the object can also be a complete copy; Deep copy: Think: How can you make deep copy by simply modifying shallow copy code?

Function deepClone(obj) {// Return the same object if(typeof obj! ="object"){return obj} var newObj = {}; for (var key in obj) { newObj[key] = deepClone(obj[key]) } return newObj; } var newXm = deepClone(xm); newXm.name = "Dm"; newXm.cars.bmw = "40w"; console.log(newXm); console.log(xm)Copy the code

Optimized deep copy:

Function deepClone(obj) {// Return the same object if(typeof obj! ="object"){return obj} var newObj = {}; for (var key in obj) { newObj[key] = deepClone(obj[key]) } return newObj; }Copy the code

Null var o=deepClone(null) console.log(o) Object: proto:Object 2 Regular expression var RegExp = /[\u4e00-\u9fa5]/gm; Var o = deepClone(RegExp) console.log(o) Object: proto:Object 3 Date object var RegExp=/[u4e00-u9fa5]/gm; Var o=deepClone(RegExp) console.log(o) {}: => Object

function deepClone(obj) { if (obj === null) return null; If (obj instanceof RegExp) return new RegExp(obj); If (obj instanceof Date) return new Date(obj); If (typeof obj == 'Function') return new Function (obj){}; typeof obj == 'Function') return new Function (obj){}; // Function case if (typeof obj! Return obj} // [].__proto__. Constructor =Array() // Constructor =Object() var newObj = new obj.__proto__. Constructor; for (var key in obj) { newObj[key] = deepClone(obj[key]) } return newObj; }Copy the code

Test code:

Var obj={name: 'xm', birth: new Date, desc: null, reg: /^123$/, ss: [1,2,3], fn: function(){ console.log('123') } } var obj2 = deepClone(obj); console.log(obj,obj2) obj.fn() obj2.fn()Copy the code

Another set of code:

function deepCopy(target){ let copyed_objs = []; Function _deepCopy(target){if((typeof target! == 'object')|| ! target){return target; } for(let i = 0; i < copyed_objs.length; i++){ if(copyed_objs[i].target === target){ return copyed_objs[i].copyTarget; } } let obj = {}; if(Array.isArray(target)){ obj = []; / / processing target is an array of} copyed_objs push ({target: target, copyTarget: obj}) Object. The keys (target). The forEach (key = > {the if (obj [key]) { return; } obj[key] = _deepCopy(target[key]); }); return obj; } return _deepCopy(target); }Copy the code

Copyed_objs is an array that holds recursive target objects. Before recursing to a target object, we should examine the array; If the current target object is equal to an object in copyed_objs, it does not recurse. This solves the problem of circular and identical references. Test code:

Var a = {arr:[1,2,3,{key:'123'}]; a.self = a; Mon1 = {name:' CCC '}; a.common2 = a.common1; Var c = deepCopy(a); c.common1.name = 'changed'; console.log(c);Copy the code

Results:

Bring about {arr: Array (4), the self: {.. },common1:{.. },common2:{.. }} bring arr (4) [1, 2, 3, {...}] bring common1: {name: "changed"} bring common2: {name: "changed"} bring self: {arr: Array (4), the self: {.. },common1:{.. },common2:{.. }} bring __proto__ : ObjectCopy the code

Common business requirements using JSON method and for… In plus recursion.

1.JSON.parse(JSON.stringify(obj)) 2.function isObj(obj) { return (typeof obj === 'object' || typeof obj === 'function') && obj ! == null } function deepCopy(obj) { let tempObj = Array.isArray(obj) ? [] : {} for(let key in obj) { tempObj[key] = isObj(obj[key]) ? deepCopy(obj[key]) : obj[key] } return tempObj }Copy the code

10. 常考 : How do I implement trim() with regulars?

Code:

String. The prototype. The trim = function () {return this. The replace (/ ^ s + | \ s + $/ g, ' ')} / / or function trim (String) {return string.replace(/^\s+|\s+$/g,'') }Copy the code

How to implement inheritance without class? How do you do that with class?

Code: Don’t implement class like this:

Function Animal(color){this.color = color} animal.prototype. Move = function(){ Animal.call(this,name) this.name = name} dog-prototype. __proto__ = animal. prototype function temp(){} Temp. Prototype = Animal. The prototype t prototype = new temp () / / let the Dog prototypal inheritance Animal prototype t prototype. The constructor = Dog Function (){console.log(' Dog ')} var Dog =new Dog(' yellow ',' yellow ')Copy the code

This implements an animal class, and then implements a dog class, and the dog class inherits from animal, with three points. The first is whether to call animal from one constructor, and animal from dog, and return this and all arguments. Second: implement the inheritance of the prototype; Third: change constructor to Dog. Using class is relatively simple:

class Animal{
   constructor(color){
      this.color = color
   }
   move(){}
}
class Dog extends Animal{
   constructor(color,name){
      super(color)
      this.name = name
   }
   say(){}
}
Copy the code

There are two points for using class, one for using extends and the other for calling super


12. How to implement array deduplication?

Hash 2.[…new Set(array)] // Hash 2.[…new Set(array)

function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return } return [...new Set(arr)] }Copy the code

WeakMap // Supports all types of deweighting


13. == Related topics? (Reverse answer)

Price ratio 1 == “”? Var a = 1; var a = 1; var a = 1; var b = true; console.log(a == b); //true === complex type [], {}, NAN is not equal, other equal


14. Write a Promise by hand

Said ideas? A Promise has three states: Pending initial; Depressing success; Rejected Indicates the failed state.

function Promise(executor) { let self = this; self.status = 'pending'; // wait state self.value = undefined; Self. reason = undefined; Function resolve(value){if(self.status === 'pending'){self.status = 'resolved'; self.value = value; } } function reject(reason) { if(self.status === 'pending') { self.status = 'rejected'; self.reason = reason; } } try{ executor(resolve, reject); }catch(e){ reject(e); // An exception occurred during the capture. Prototype. Then = function (onFufiled, false) {//onFufiled = false; //onFufiled = false; onRejected) { let self = this; if(self.status === 'resolved'){ onFufiled(self.value); } if(self.status === 'rejected'){ onRejected(self.reason); } } module.exports = Promise;Copy the code

15. What is a callback function?

According to MDN, a callback function is a function that is passed as an argument to another function, and then performs some kind of operation by calling the callback function inside the external function. Simply put, a callback is a function that will be executed immediately after another function completes execution. A callback function is a function passed as an argument to another JS function. The callback function is executed inside the function passed. Functions are treated as a class of objects in JavaScript. For a class of objects, exponents, functions, or variables can be the same as other entities in the language. You can also pass functions as variables to other functions and return them from other functions. Functions that can perform this operation are called higher-order functions. The callback function is actually a pattern. The word “pattern” denotes a proven approach to solving common problems in software development. It is best to use the callback function as a callback mode. Why do we need a correction? Client-side JavaScript runs in the browser, and the browser’s main process is a single-threaded event loop. If we try to run a long-running operation in a single-threaded event loop, the process is blocked. This is technically bad because the process stops processing other events while waiting for the operation to complete. For example, the alert statement is considered one of the blocking codes in javascript in the browser. If you run Alert, you won’t be able to interact in your browser until you close the Alert dialog window. To prevent blocking long-running operations, we use a callback.


16. What is the difference between Typeof and Instanceof?

Typeof can determine basic datatype (except for null datatype object bug), and can correctly determine whether an object is function. Other datatype,Array, and other datatype cannot be determined. Instanceof, on the other hand, can accurately determine complex data types, but not simple data types. Prototype chain of instance objects?


Post outside the topic

1. Check whether the string is composed of a letter, followed by letters, digits, and underscores (_). The total length of the string is 5-20 (program).

Var/c = ^ [a-z | a - z] {1} | _ [/ w] {4} 3 /; C.t est (" STR ");Copy the code

2. Intercept the efG of the string abcdefg (program)

 var str='abcdefg';
 alert(str.substring(4));
Copy the code

Or use re: it is also troublesome to use

var str = 'abcdefg'; var re= /efg/; The (STR) if (re) {var efg = STR. The substring (STR) indexOf (' efg)); Alert (efg)} // indexOf() : method returns the position at which a specified string value first appears in the string. // substring: If there is only one argument, where does it start and endCopy the code

Or:

<script type="text/javascript"> window.onload=function test() { var str = "abcdefg"; If (/efg/.test(STR)){var efg = str.substr(str.indexof ("efg"), 3); alert(efg); } } </script>Copy the code

3. Determine the most frequent occurrence of a character in a string and count the number (program)

First, store each STR entry in JSON, then iterate through the JSON data to find the maximum number and the corresponding key.

var str = 'qweqrtyuiqqqwrtyudfgerqtywer'; var result = maxN(str); Function maxN(STR) {// Define a JSON object to hold each item of STR and the number of occurrences. var json = {}; Value for(var I =0; var I =0; i<str.length; I++){// check whether the current STR value is in json if(! Json [str.charat (I)]){// Add the current value to json if it does not exist, and set 1 json[str.charat (I)] = 1; } else {// Make the value of the existing value in the array ++ if it exists; json[str.charAt(i)] ++; Var number = ''; var num = 0; For (var j in json){if (json[j]>num) {if (json[j]>num) {// Let the current value change to the maximum number of values of num = json[j]; number = j; }} return {number:number, num:num}} document.write(' this string occurs '+ result.num +' times '+ result.number);Copy the code

Method 2. Use the array reduce() method; Apply a function to both values of an array (left to right)

var str = 'qweqrtyuiqqqwrtyudfgerqtywer'; var result = maxN(str); Function maxN(STR) {// Define a JSON object to hold each item of STR and the number of occurrences. var json = str.split('').reduce((m, n) => (m[n]++ || (m[n] = 1), m), {}); Var number = ''; var num = 0; For (var j in json){if (json[j]>num) {if (json[j]>num) {// Let the current value change to the maximum number of values of num = json[j]; number = j; }} return {number:number, num:num}} document.write(' this string occurs '+ result.num +' times '+ result.number);Copy the code

Method 3: Use regular expression replace to check each item of STR:

var str = 'qweqrtyuiqqqwrtyudfgerqtywer'; var result = maxN(str); function maxN(str){ var json = {}; str.replace(/(\w{1})/g,function($1){ json[$1] ? json[$1]+=1 : json[$1] = 1; }); Var number = ''; var num = 0; For (var j in json){if (json[j]>num) {if (json[j]>num) {// Let the current value change to the maximum number of values of num = json[j]; number = j; }} return {number:number, num:num}} document.write(' this string occurs '+ result.num +' times '+ result.number);Copy the code

4. Write a method to remove duplicate elements from an array

1. Traversal number group method of the simplest method to duplicate, implementation ideas: create a new array, traversal the incoming array, the value of the new array is not added to the new array; Note: The “indexOf” method is ECMAScript5, which is not supported by IE8.

Function unique1(array) {var n = []; For (var I = 0; i < array.length; If (n.idexof (array[I]) == -1) n.push(array[I]); if (array[I]) == -1) n.push(array[I]); } return n; } if (! Ecma5) {if (! Ecma5) {if (! Ecma5) { Array.prototype.indexOf = function(item) {var result = -1, a_item = null; if (this.length == 0) { return result; } for (var i = 0, len = this.length; i < len; i++) { a_item = this[i]; if (a_item === item) { result = i; break; } } return result; }}Copy the code

2. Object key-value pair method This method executes faster than any other method, but occupies a large amount of memory; Implementation idea: create a new JS object and a new array, traversing the incoming array, judge whether the value is the key of the JS object, if not, add the key to the object and put into the new array. Note: toString() is automatically executed on the incoming key to determine whether it is a JS object key. Different keys may be mistaken for the same; For example, a[1], a[“1”]. To solve the above problem, “indexOf” is called again.

Function unique2(array) {var n = {}, r = [], len = array.length, val, type; for (var i = 0; i < array.length; i++) { val = array[i]; type = typeof val; if (! n[val]) { n[val] = [type]; r.push(val); } else if (n[val].indexOf(type) < 0) { n[val].push(type); r.push(val); } } return r; }Copy the code

If the first occurrence of the i-th item in the current array is not I, then the i-th item is repeated and is ignored. Otherwise, store the result array.

function unique3(array) { var n = [array[0]]; For (var I = 1; i < array.length; I ++) {// If the first occurrence of the i-th item in the current array is not I, then the i-th item is repeated and ignored. If (array.indexof (array[I]) == I) {n.ush (array[I]); } } return n; }Copy the code

Although the “sort” method of native arrays is not very reliable, it has no effect on sequential de-sorting. Sort the incoming array, sort the same values adjacent to each other, and then run through the new array to only add the value that does not duplicate the previous value.

Function unique4(array) {array.sort(); function unique4(array) {array.sort(); var re = [array[0]]; for(var i = 1; i < array.length; i++) { if(array[i] ! == re[re.length - 1]) { re.push(array[i]); } } return re; }Copy the code

5. Optimization traversal number group method implementation idea: get no repeat the rightmost value into a new array. (Terminate the current cycle and enter the next round of judgment of the top cycle when duplicate values are detected)

Function unique5(array) {var r = []; for (var i = 0, l = array.length; i < l; i++) { for (var j = i + 1; j < l; j++) { if (array[i] === array[j]){ j = ++i; r.push(array[i]); } } } return r; }Copy the code

5. How does JavaScript detect if a variable is a String? Please write the function implementation method 1:

function isString(obj){ return typeof(obj) ==="string"? true:false; } alert(a(123)); alert(a("abc"));Copy the code

Method 2:

function isString(obj){ return obj.constructor === String? true:false; } alert(a(123)); alert(a("abc"));Copy the code

Method 3:

function isString(obj){ return Object.prototype.toString.call(obj) === "[object String]"? true:false; }Copy the code

Method 4:

function type(data){ return Object.prototype.toString.call(data).slice(8,-1).toLowerCase(); } alert(type(123)); alert(type("abc")); Varisstring = isString('xiaoming'); console.log(isstring); // trueCopy the code

6. How do I show/hide a DOM element?

1. The hidden control of the style property no longer occupies the position of the display: Enclosing getElementByXid (‘ domXid.) style. The display = “none” enclosing getElementByXid (‘ domXid) style. The display = “block” 2. The hidden control only makes the control invisible, and the control remains in its original position: Enclosing getElementByXid (‘ domXid.) style. The visibility = “hidden” enclosing getElementByXid (‘ domXid) style. The visibility = “visible” 3. Control display hide using jQuery: (enclosing getElementByXid (‘ domXid). Hide () (enclosing getElementByXid (‘ domXid). Hide () (enclosing getElementByXid (‘ domXid). Hide () (enclosing getElementByXid (‘ domXid)), show () 4. Use bind-visible KO object or data component field to control hiding. After hiding, dom nodes are actually still in details: doc.wex5.com/data-bind-v… 5. Bind KO object or data component field by bind-if to control hiding. After hiding, dom node no longer exists. Note that bind-visible controls the presence of all elements under the current DOM node (including the current node) while bind-visible controls the presence of all elements under the current DOM node (including the current node)

7. Front-end development optimization problem?

(1) reduce the number of HTTP requests: CSS Sprites, JS, CSS source compression, image size control appropriate; Web Gzip, CDN hosting, data cache, picture server. (2) Front-end template JS+ data, reduce bandwidth waste caused by HTML tags, front-end variables to save AJAX request results, each operation of local variables, no request, reduce the number of requests. (3) Use innerHTML instead of DOM operations to reduce DOM operations and optimize javascript performance. (4) Set className instead of style when there are many styles to set. (5) Use less global variables and cache the results of DOM node search. Reduce I/O read operations. Avoid using CSS Expression, also known as dynamic-properties. (7) Image preloading, style sheets at the top, scripts at the bottom with time stamps. (8) 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. Summary: 1. Reduce the number and size of CSS, JS files (reduce repetitive code, code reuse), compress CSS and JS code 2. Image size 3. Place CSS style sheets at the top and JS at the bottom of the page 4. Reduce HTTP requests 5. Use external Js and CSS

8. Write the sum from 1 to 100 in JS recursively.

If you were asked, would you write:

var sum = 0; for(var i=1; i<=100; i++){ sum += i; } console.log(sum); / / 5050Copy the code

So how does JavaScript recursively evaluate the sum from 1 to 100? Analysis: Assuming the recursive function is already written, sum(100) is the sum of 1-100. Find a recursive relation: that is, the relation between n and n-1, or n-2:

sum(n) == sum(n-1) + n var resulst = sum(100); var resulst = sum(99) + 100; .Copy the code

1. Transform a recursive structure into a recursive body

 function sum(n){
   return sum(n-1) + n;
 }
Copy the code

At this point, we need an important step, which is the critical value, to prevent the program from infinite loop 2, add the critical condition to the recursion to get 100 to get 99 to get 99 to get 98 to get 98 to get 97… Sum (1) = 1

function sum(n){ if(n==1) return 1; return sum(n-1) + n; } var amount = sum(100); console.log(amount); / / 5050Copy the code

9. Please provide at least two asynchronous loading JS schemes.

By default, javascript is loaded synchronously, which means that the loading of javascript is single threaded, and the following elements can only be loaded after the loading of javascript is complete. For some javascript that is not very meaningful, if it is placed in the header, it will cause slow loading. Will seriously affect the user experience. Asynchronous loading mode: (1) defer, which only supports IE. (2) Async: (3) Create script and insert it into DOM. After loading, callBack is shown in the code:

function loadScript(url, callback){ var script = document.createElement("script") script.type = "text/javascript"; if (script.readyState){ //IE script.onreadystatechange = function(){ if (script.readyState == "loaded" || script.readyState == "complete"){ script.onreadystatechange = null; callback(); }}; } else { //Others: Firefox, Safari, Chrome, and Opera script.onload = function(){ callback(); }; } script.src = url; document.body.appendChild(script); }Copy the code

10. Please write at least two ways to bind events in jQuery

Short events: Click, hover, mousemove, mouseup, mousedown… JQuery provides four types of event listening methods: bind, live, Delegate, and ON. The corresponding unbind, die, undelegate, and off functions are used to unbind events. Before we start, we will declare an example, the use of each function around this example, and declare a function to be used as a listener function, the JS code is as follows:

  function getHtml(){
    alert(this.innerHTML);
  }
Copy the code

1, the bind (type, [data], function (eventObject))

Bind (click, change, mouseover, etc.) binds a listener of a specific event type to the selected element. Data: The argument passed to the listener function, which is retrieved by event.data. Optional; Function: a listener function, which can pass in an Event object. The event object is a jQuery encapsulated event object, which is different from the original event object. Let’s take a look at the source of bind:

bind: function( types, data, fn ) {
  return this.on( types, null, data, fn );
}
Copy the code

So you can see internally that we’re calling the on method, so what does that on look like? We’ll look at that later. $(‘#myol li’).bind(‘click’,getHtml); The thing about BIND is that it binds listeners to the target element, one at a time, and it’s fine to use it when elements on the page aren’t being added dynamically. But if a list element 5 is added dynamically to the list, clicking on it will not respond and you must bind it again. To take the hassle out of it, we can use Live. JQuery also has a shorthand for event binding such as a.lick (function(){}); , a.c hange (function () {}); They are just shorthand, like bind.

2, live(type, [data], fn)

Live has the same parameters as bind.

live: function( types, data, fn ) {
  jQuery( this.context ).on( types, this.selector, data, fn );
  return this;
}
Copy the code

You can see that the live method does not bind the listener to itself (this), but to this.context. What is this context? This is the scope of the element, as shown in the following code:

$('#myol li').context; //document
$('#myol li','#myol').context; //document
$('#myol li',$('#myol')[0]); //ol
Copy the code

In general, we don’t use selectors like the third way, so we assume that the context is always document, that the live method binds the listener to document. Instead of tying listeners directly to elements, do you think of event delegates? If not, click here to recall. Live uses the event delegation mechanism to complete the monitoring of events and delegates the processing of nodes to Document. In the listener function, we can use event.currenttarget to get the node where the event is currently captured. $(‘#myol li’). Live (‘click’,getHtml); The advantage of using event delegates is that newly added elements do not have to bind listeners again. Bind: Bind: Live: Bind: Live: Bind Is that ok? The answer is no, and a big no. Because listeners are tied to the document, event processing has to wait for layers of bubbling until it reaches the root node, which can have unexpected results when the DOM tree is deep or the nesting of nodes is complex, and the root node is too much of a burden. Like four, five, or even eight generations under one roof (unlikely in reality, but in HTML there’s probably a lot more hierarchy), the Don couldn’t remember which grandchild belonged to which son, and which great-grandchild belonged to which son, and he got confused and did things wrong. To this end, jQuery has officially announced that live will be deprecated in version 1.7 and replaced by other methods. So we follow the call and stop using it. Because of that shortcoming of Live, we wondered if we could attach our listeners to the nearest parent element instead of the document. Following normal logic, a delegate was born.

3, the delegate (selector, type, [data], fn)

The selector argument specifies the target element that fires the event, and the listener will be bound to the element that calls the method. Delegate: function(selector, types, data, fn) {return this.on(types, selector, data, fn); } again calls on, and passes the selector to ON. It seems that the on really matters. So let’s ignore it. Take a look at sample first: $(‘ # myol). The delegate (‘ li ‘, ‘click’, getHtml); In our example, we bind listeners to OL, and event.currenttarget shows that the element currently captured for the event is OL. This gives us a little more flexibility in our choices, not only with event delegates, but also with whom to delegate. After all, it’s not nice to always ask the same person for help. You need to be very strategic about how you choose your delegate objects, because there can be many parent elements. I think the rule should be to choose the most recent “stable” element, which is chosen because events bubble up faster and can be processed in the first place. “Stable” means that the parent element is on the page from the beginning, is not added dynamically, and will not disappear in the future, so that it can always monitor its children. If you can’t wait to see what this on really looks like, here it is:

4.on(type,[selector],[data],fn)

The delegate argument is pretty much the same as the delegate argument, but there are subtle differences. First, the type and the selector are switched, and second, the selector becomes optional. The reason for the switch is hard to verify, but it’s probably to make it more visually comfortable. $(‘#myol li’).on(‘click’,getHtml); As you can see, event.currenttarget is Li itself, which has the same effect as bind. And when you pass in a selector, it’s exactly the same as a delegate, except that the order of the arguments is different. Now that WE’ve seen on in action, how do we choose from so many event-binding options? In fact, this question is completely unnecessary, because you already know the difference between them, don’t you? Use it as you see fit. However, the official recommendation is to use on as much as possible. Since all other methods are done internally, using ON directly can be more efficient, and you can completely use ON instead of the other three methods. As for how to replace I think there is no need to write out so straightforward, really understand the difference between them after the natural is not difficult.

11. CORS said

1.CORS is the abbreviation of Cross Origin Resource Sharing, which means cross-domain Resource Sharing in Chinese. The technology achieves the purpose of obtaining the data of the domain name by returning the CORS response header after the target domain name 3. The core of this technology is to set response header, which is divided into simple request and complex request 4. For simple requests, you only need to set access-Control-allow-Origin: destination source. For complex requests, there are two steps: the first step is for the browser to initiate an OPTIONS request, and the second step is for the actual request. OPTIONS requests need to indicate the actions supported by the server in the response header. Such as Access – Control – Allow – the Methods: POST, GET, OPTIONS, is another important response header Access – Control – Allow – Credentials: true Cookie 5 to indicate whether to accept the request. The advantage is that you can cross domains with simple configuration 6. The disadvantage is that some older browsers do not support CORS or Credentials 7. The solution is to use JSONP or P3P technology

12. The height of the div is equal to the height of the browser’s visible area. When the browser scrolls, the div always covers the entire visible area of the browser.

  window.onscroll = function(){
     var divObj = document.getElementByIdx_x_x("floatDiv");
     var topDistance = parseInt(document.documentElement.scrollTop + document.body.scrollTop);
     divObj.style.top = topDistance + "px";  
  }
Copy the code

Code description: window. Onscroll scroll event document. The documentElement. ScrollTop or document. The body. The scrollTop as: cut web pages. Code of the document. The documentElement. ScrollTop + document. The body. The scrollTop, so to write, because: Internet explorer, Firefox identification document. DocumentElement. ScrollTop, and in chrome, and this is 0, chrome identification document. The body. The scrollTop.

13.1 The meanings of rem, 1em, 1vh and 1px respectively

1rem means that all the length is relative to the root element, which is usually done by giving HTML elements a font size and then other elements a rem length; The length of the 1 em a byte, said the child font size relative to the parent font size, element width/height/margin/padding with em is relative to the element of the font – size; 1vh represents 1% of the height of the screen (browser), a unit of relative length 1px; Pixel PX is relative to the screen resolution of the monitor.

14. A fixed-width element in the browser (IE6, IE7, Firefox) is horizontally centered and aligned.

(Write the main HTML tags and CSS ideas)

15. Horizontally centered and vertically centered (at least four)

1.

16. What are the ways in which CSS is introduced? What’s the difference between link and @import?

In HTML design, CSS can be introduced in four ways. Inline STYLE, also known as inline STYLE, adds the STYLE attribute directly to the individual component tag, < component (tag) STYLE=” property (attribute)1: set value 1; Property (Attribute)2: Set value 2; . } the sample:

<td style="color:#c00; font-size:15px; line-height:18px; > </td>Copy the code

This is usually a bad way to write, and it can only change the style of the current tag if you want more than one

Having the same style, you have to repeat it for each

Add the same style.


If you want to change a style, you have to change all the code in the style. Obviously, the introduction of INLINE CSS code leads to verbose HTML code and makes web pages difficult to maintain.


The advantage of this approach is that styles can be neatly applied to individual tags. Easy to use when writing code.


Disadvantages of this approach: there is no “unity” of the entire document and it can be difficult to modify a style when needed.


Method 2: Embed Styles (internal reference CSS)


Embedding refers to writing CSS code under a tag in the HTML header. Example:

<head>
    <style>
      .content {
        background: red;
     }
    </style>
</head>
Copy the code

structure is written in the section of the page. The advantage of this approach is that as long as there is uniformity throughout the article, declared components will apply the style rule. Disadvantages of this method: the flexibility of individual components is insufficient, and the functionality of the whole station is weak. Embedded CSS only works on the current page. Because the CSS code is in an HTML file, it makes the code more centralized, which is often advantageous when we write template web pages, where the viewer of template code can see the HTML structure and CSS styles at a glance. Because the embedded CSS is only valid for the current page, this can lead to code redundancy and maintenance problems when multiple pages need to introduce the same CSS code. Link style refers to the use of tags in the HTML header to import external CSS files. Example: Write style rules in a.css style file and import them as tags. Suppose we save our style rules as an example.css file, we just add:

<link rel=stylesheet type="text/css" href="example.css">Copy the code

Once you import the CSS stylesheet file, you can directly apply the styles specified in the style file. The link tag is usually written in a part of the web page. The advantage of this method is that you can specify several files to apply the same style rules into the same style file, which can be modified uniformly, and it is convenient for the whole site to have a uniform style. Common CSS web layouts use this method. Disadvantages of this approach: lack of flexibility in individual files or elements. Mode 4: Import styles (External reference @import references CSS) The import mode refers to using CSS rules to import external CSS files. Example:

<style type="text/ CSS "> @import url(CSS /example.css); </style>Copy the code

Or write it in A CSS style

@charset "utf-8"; @import url(style.css); *{ margin:0; padding:0; } .notice-link a{ color:#999; }Copy the code

What’s the difference between link and @import? Difference 1: Link is an XHTML tag. In addition to loading CSS, it can also define RSS, rel connection properties, and other transactions. @import belongs to CSS and can only load CSS. Difference 2: When link references CSS, the page is loaded at the same time; @import requires the page to be loaded after the page is fully loaded. So there will be no CSS style at the beginning of the page, flashing the style (in the case of slow network speed) difference 3: compatibility difference. Link is an XHTML tag with no compatibility issues. @import was introduced in CSS2.1, not supported in older browsers, IE5 and above. Difference 4: Link supports using JavaScript to control the DOM to change styles; @import is not supported.

17. Understanding of HTML5 and CSS3

New features for CSS3 and HTML5: juejin.cn/post/684490… HTML5 & CSS3 interview question: juejin.cn/post/684490…

18. What are the advantages of web standard sites?

A, Web standardization can enhance browser compatibility Second, the standardization of Web can improve the standardization of the development team code, the development of high efficiency and simple maintenance, Web information standardization good for SEO, cross-platform availability five, reduced cost of server through the style of reuse, the decrease of the amount of files can be multiplied, the site Makes it possible to reduce the cost of server bandwidth. Especially for large portal sites, the larger the number of pages means the more code is reused, which reduces the data access of the server at the same time and reduces the bandwidth usage.

HTML is responsible for building the basic structure of a web page; CSS is responsible for designing the presentation of web pages; JavaScript is responsible for developing the interactive effects of web pages. Web page structure: Web page standards mainly organize and classify page information in web pages, and structured standard languages mainly include XML, HTML and XHTML.

  1. XML

XML, short for The Extensible Markup Language, is a Language that defines other languages. XML was originally designed to make up for the shortcomings of HTML and meet the needs of web information publishing with powerful extensibility. XML is now primarily used as a data format for network data exchange and writing configuration files. The XML recommendation is XML 1.0, published by the W3C on October 6, 2000, at www.w3.org/TR/2000/REC… HTML is the abbreviation of HyperText Markup Language, which is translated into Chinese as “HyperText Markup Language”. XHTML 1.0 is based on HTML 4.0, and extends it with XML rules. The original purpose of publishing XHTML was to facilitate the transition from HTML to XML. In general contexts, people tend to use HTML instead of HTML and XHTML. The HTML recommendation is XHTML1.0, released by the W3C on January 26, 2000, at www.w3.org/TR/xhtml1/. Webpage behavior: the behavior standard mainly controls the structure and display of webpage information logically and realizes the intelligent interaction of webpage. Behavioral standard languages include document object models (e.g. W3C DOM) and EMAScript.

  1. DOM

DOM is an acronym for Document Object Model. According to the W3C DOM specification (www.w3.org/DOM/), DOM is a language that allows browsers to communicate with web content, enabling users to access page elements and components. ECMAScript ECMAScript is a standard scripting language developed by the Organization for the European Computer Manufactures Association (EMA).

Is currently the most widely used ECMAScript 262, namely the JavaScript version 5.0, reference address is: www.ecma-international.org/publication…