There is no answer in the previous blog , Now I have time to sort it out and send it out , Hope to help you who are looking for a job , Or that sentence : Technology is its own thing only when it really understands it , Mutual encouragement .

Web Front end written test questions

Html+css

1. Yes WEB Standards and w3c Understanding and understanding of .

Label closed , Tag lowercase , Don't nest randomly : Improve the search probability of the search robot ;

Using extranet css and js, The separation of structural behavior : Faster file download and page loading , Content can be accessed by a wider range of devices ;

Less code and components : Easy to maintain , The revision is convenient , There is no need to change the content of the page , Provide a printed version without copying content , Improve the usability of the website .

2.Xhtml and html What's the difference? .

Html( Hypertext markup language ) It's an application of standard general markup language , It's also a norm , A standard .

Xhtml( Extensible HyperText Markup Language ) It's a markup language , Ways of expression and html similar , But the grammar is more strict , The main difference :

1, All elements must be nested correctly ,

2, All markings must be closed ,

3, Tag name , Property names must be lowercase ,

4, All attributes must be in “” Cover up ,

5, All that's not part of the label ><& All have to be coded ,

6, All properties must have values ,

7, Don't have... In the comments --

8, Pictures must have captions

3.css What are the ways to introduce ?link and @import Is the difference between the ?

Four kinds of : inline , Embedded , Outside the chain , Import

difference :

1,link Belong to xhtml label ,@import Totally css One way to provide ,link In addition to loading css You can also define rss, Definition rel Properties, etc ,@import Load only css.

2, The loading order is different :link Refer to the css It's loaded at the same time ,@import Refer to the css It will not be loaded until all pages are downloaded .

3, Compatibility differences ,@import yes css2.1 Put forward ,ie5 The above supports ,link No compatibility issues .

4, Use dom Control the difference in style , When used javascript To control the style , Only use link,@import No dom It's controllable .

5,@import Can be in css Introduce other style sheets again in .

4.css What are the selectors ? Which attributes can be inherited ? How to calculate the priority ? Inline and important Which priority is higher ?

Tag selector , Class selector ,id Selector

Inherited is not as good as specified ,id>class>Tagname

Important High priority

5. What are the three layers of front page , What are the differences ? What is the role ?

The structure layer :html

from html perhaps xhtml Responsible for creating , Use tags to describe the meaning of web content .

The presentation layer :css

from css Responsible for creating , Answer how to display the relevant content .

Behavior layer :javascript

from javascript Responsible for creating , Responsible for answering how to respond to events .

6.css The basic sentence structure of ?

Selectors , attribute , Property value

7. Which browsers have you tested for compatibility ? What are the cores of these browsers ?

Ie(ie kernel ), firefox (Gecko), Google (webkit),opera(presto)

8.<img> On the label title And alt What is the difference between attributes ?

Alt It's a prompt message displayed on the page when your picture can't be loaded for some reason , It will output directly where the image was originally loaded ,title It's a little tip displayed on the picture when the mouse hovers over it , The mouse is gone , Great number html Tags support title.

9. Write several IE6 BUG Solutions for

1. Double margins BUG float Caused by the   Use display

2.3 Pixel problem Use float Caused by the Use dislpay:inline -3px

3. Hyperlinks hover Invalid after clicking   Use correct writing order link visited hover active

4.Ie z-index problem Add to parent position:relative

5.Png transparent Use js Code Change

6.Min-height Minimum height !Important solve ’

7.select stay ie6 Under cover Use iframe nesting

8. Why there is no way to define 1px Left and right width containers (IE6 Caused by the default row height , Use over:hidden,zoom:0.08 line-height:1px)

10. describe css reset Function and use of .

Css reset Reset the browser's default css style , Different types of browsers , The default style is different , By using css reset Reset , Let them unite , Easy to develop .

11. How do you optimize the files and resources of the website ? The expected solutions include :

1, Reduce... As much as possible http Number of requests ( File merge )

2, Use CDN( Content distribution network )

3, add to Expire/Cache-Control head

4, Enable Gzip Compress

5,css Put it at the top of the page

6,scrip At the bottom of the page

7, To avoid the css Use in Expressions

8, hold js and css Put it in an external file

9, Reduce dns Inquire about

10, Compress javascript and css

11, Avoid redirects

12, remove duplicate scripts

13, Configure entity tags

14, Use ajax cache

12. What is semantic html?

Structured by content ( Semantic content ), Choose the right label ( Code semantics ), It is convenient for developers to read and write more elegant code, and at the same time, it makes the crawler and machine of browser better parse .

13. There are several ways to clear floats ? Their advantages and disadvantages are ?

1, Parent definition height( advantage : Less code , Easy to master ; shortcoming : Only suitable for fixed height elements , Can't be highly adaptive )

2, Use the empty label at the end to clear the float :Clear:both( advantage : Theoretically, it can clear all the floating labels , Simple code less, good browser support ; shortcoming : Added meaningless tags )

3, The parent defines the pseudo class after and zoom( advantage : Good browser support ; shortcoming : Lots of code , Only by combining two sentences of code can mainstream browsers support )

4, Parent definition overflow:hidden( advantage : Less code , Simple , Good browser support ; shortcoming : Must define width perhaps zoom, Cannot define at the same time height, Unable to join position In combination with )

5, Parent definition overflow:auto( advantage : Less code , Simple , Good browser support ; shortcoming : Must define width perhaps zoom, Cannot define at the same time height, If the height of an internal element exceeds its parent, a scroll bar will appear )

also , The parents float together , Parent definition display:table, Add... At the end br Of clear:both etc.

14. What's the difference between browser standard mode and weird mode ?

The so-called standard model refers to , Browser press W3C Standard parsing execution code ; Weird mode is to use the browser's own way to parse the execution code , Because different browsers parse in different ways , So we call it weird patterns . Whether browser parsing uses standard mode or weird mode , With the DTD Statement directly related ,DTD Declaration defines the type of standard document ( Standard pattern analysis ) The document type , Will make the browser use the corresponding way to load the web page and display , Ignore DTD Statement , Will put the page into weird mode (quirks mode).

In standard mode

IE6 incognizance !important Statement ,IE7、IE8、Firefox、Chrome Wait for the browser to know ; And in weird mode ,IE6/7/8 I don't know !important Statement

15. Explain CSS sprites, And how you want to use it on a page or website

Is a web page image application processing . It allows you to include all the scattered pictures involved in a page in a large picture , thus , When visiting this page , The loaded pictures will not be displayed slowly as before .

page icon In many cases, it's appropriate to use .

16. Discuss CSS hacks, Conditional references or other ?

Every browser knows , Here to firefox use ;

\9 be-all ie The browser recognizes ;

\0 It's for ie8 Of

+ + ie7 Set the ;

_ _ Dedicated to the magic ie6;

:root #test { } :root It's for ie9 Of ,

@media all and (min-width:0px){ #test {} } This is always with ie Rush to recognize \0 It's amazing opera, You have to add \0, Otherwise firefox,chrome,safari We all know ...

@media screen and (-webkit-min-device-pixel-ratio:0){ #test {} } Finally, this is the browser upstart chrome and safari Of .

<!--[if IE 6]><link href="ie6.css" />< ![endif]--> The only way to annotate this is IE Browser support , Other browsers just think of it as html notes , It doesn't work . In general use JavaScript Or server-side program judgment User Agent.

17. Explain how the browser determines whether an element matches a CSS Selectors ?

Judge from back to front . The browser first generates a collection of elements , This set is often generated by the index of the last part ( If there is no index, it is a collection of all elements ). And then match up , If not in accordance with the previous section , Just delete the element from the collection , Until the real selectors match , The elements that are still in the collection match the selector .

18. Can you describe the difference between progressive enhancement and elegant degradation ?

Progressive enhancement progressive enhancement: Build a page for a lower version browser , Guarantee the most basic functions , And then for the advanced browser effect 、 Interaction and other improvements and additional functions to achieve a better user experience .

graceful degradation graceful degradation: Build full functionality from the beginning , And then compatible with lower version browsers .

difference : The elegant degradation starts with the complicated status quo , And try to reduce the supply of user experience , And incremental enhancement comes from a very basic , The working version starts , And continue to expand , To meet the needs of the future environment . Downgrade ( Functional attenuation ) It means looking back ; And incremental enhancement means looking forward , At the same time, ensure that its foundation is in a safe place .

19.CSS Capital letters ?

text-transform value :
Capitalize The initials of Pinyin are capitalized
Uppercase All alphabets are capitalized
Lowercase Pinyin is all lowercase

20.CSS What are the selectors

  • descendent selector ( use HTML Label statement )
  • id Selectors ( use DOM Of ID Affirming )
  • Class selectors ( Declare... With a style class name )
  • Attribute selector ( use DOM Attribute declaration of , Belong to CSS2,IE6 I won't support it , Not commonly used , I don't know )

Except before 3 Two basic selectors , There are also some extension selectors , Include

  • Descendant selector ( Use space spacing , such as div .a{  })
  • Group selector ( Use comma intervals , such as p,div,#a{  })

21. After the hyperlink visit hover What's the problem with style ? How to solve ?

answer : The hyperlink style visited by the click no longer has hover and active 了 , The solution is to change CSS The order in which attributes are arranged : L-V-H-A(link,visited,hover,active)

22. Browsers also have default inborn inline-block Elements ( Have internal dimensions , Height and width can be set , But it doesn't wrap ), What are they? ?

answer :<input> 、<img> 、<button> 、<texterea> 、<label>.

23.px and em The difference between

PX:

PX It's actually pixels , use PX Set font size , More stable and accurate . But there is a problem with this approach , When the user browses our product in the browser Web When the page is , If you change the browser zoom , We will use our Web Page layout is broken . So for those who care about the usability of their website , It's a big problem . therefore , At this time, the use of “em” To define Web The font of the page .EM:

EM Is to scale the font size according to the benchmark .EM The essence is a relative value , It's not a specific number . This technology needs a reference point , usually <body> Of “font-size” Benchmarking . Such as WordPress Official theme Twenntytwelve Our benchmark is 14px=1em.

in addition ,em Is calculated relative to the properties of the parent element , If you want to calculate px and em Conversion between , This website is good , Just input the data px and em Calculate each other . Hit here :px and em conversion

Rem:

EM The font size is set relative to its parent element , So there's a problem , Make any element settings , You may need to know the size of the parent element . and Rem Is relative to the root element <html>, That means , We just need to determine a reference value in the root element .

Browser compatibility

except IE6-IE8r, Other browsers support em and rem attribute ,px Yes, all browsers support it .

So for browser compatibility , can “px” and “rem” Use it together , use "px" To achieve IE6-8 The next effect , And then use “Rem” To realize the effect of modern browser .

24. transparency

html{

filter:alpha(opacity=50);  /* ie It works */

-moz-opacity:0.5; /* Firefox   It works */

opacity: 0.5; /* Universal , Other browsers   It works */

}

Javascript

1.javascript Of typeof What data types are returned ?

Object,number,function,boolean,undefined;

2. enumerate 3 Cast and 2 Types of implicit type conversions .

mandatory Number(),String(),Boolean(),Object();

Implicit + - ==  if   while  for in  alert

3.Split() and join() The difference between .

Join()  Function to get a batch of strings , Then join them with a separator string , To return a string .

Split()  Function to get a string , Then break it at the separator , This returns a batch of strings .

split, It's a string of characters ( According to a separator ) It is divided into several elements and stored in an array . and Join It is to connect the strings in the array into a long string , It can be generally regarded as split The inverse operation .

4. What's the difference between event binding and normal events ?

The normal method of adding events does not support adding multiple events , The bottom event will override the top one , And event binding (addEventListener) You can add multiple .

5. Array methods pop() push() unshift() shift()

Push() Tail add pop() Tail delete

Unshift() Add... To the head  shift() Head delete

6.Ie and dom The difference between event flows ?

1. The execution order is different

2. The parameters are different

3. Event plus or not on

4.this Point to the problem

7.Ie What are the compatible writing methods with the standard ?

Var ev = ev || window.event

document.documentElement.clientWidth || document.body.clientWidth

Var target = ev.srcElement||ev.target

8.Ajax Of get and post Differences in methods ?

1、 Use Get When asked , Parameter in URL It shows that , While using Post The way is to put it in a virtual carrier , It doesn't show up .

2、 about get The way , Server side Request.QueryString Get the value of the variable , about post The way , Server side Request.Form Get submitted data . Parameters of both methods can be used Request To obtain a .

3、get Small amount of data transmitted , Not greater than 2KB.post Large amount of data transmitted , It is generally defaulted to unlimited . But in theory, , It varies from server to server .

4、get Very low security ,post High security .

5、get The request needs to pay attention to caching ,post Please don't worry about this .

6、post Request must be set Content-Type The value is application/x-form-www-urlencoded

7、 When sending a request , because get The requested parameters are all in url in , therefore send The parameter sent by the function is null, and post Request is using send When the method is used , But it needs to be given parameters

9.call and apply The difference between ?

call Method :

grammar :call(thisObj,Object)

Definition : A method that calls an object , Replace the current object with another object .

explain :

call Method can be used to call a method instead of another object .call Method to change the object context of a function from its initial context to thisObj New object specified .

If not provided thisObj Parameters , that Global Object is used as thisObj.

apply Method :

grammar :apply(thisObj,[argArray])

Definition : A method of applying an object , Replace the current object with another object .

explain :

If argArray Not a valid array or not arguments object , Then it will lead to a TypeError.

If not provided argArray and thisObj Any parameter , that Global Object will be used as thisObj, And no arguments can be passed .

10.Ajax When asked , How to parse json data ?

Use eval parse For security reasons Use parse More reliable

11. What is? javascript Local objects for , Built in and host objects ?

Local object : Independent of the host environment ECMAScript Implement the provided objects . They include :Object,Function,Array,String,Boolean,Number,Date,RegExp,Error,EvalError,RangeError,ReferenceError ,SyntaxErro,TypeError  URIError Can be instantiated .

Built-in objects Global and Math : from ECMASscript Implement the provided 、 All objects independent of the host environment cannot be instantiated .

Host object : All non local objects are host objects ECMAscript Implemented host environment provided objects . all BOM and DOM Objects are all host objects ,document,window etc. .

12.Document load and document ready The difference between ?

There are two kinds of events when the page is loaded , One is ready, Indicates that the document structure has been loaded ( Do not include non text media files such as pictures ), Two is onload, Indicates that all elements of the page, including images and other files, are loaded .

13. Write an array de duplication method .

1. Create a new array to hold the results

2. Create an empty object

3.for loop , Take out one element at a time and compare it with the object , If this element doesn't repeat , Put it in the result array , At the same time, take the content of this element as an attribute of the object , And assignment 1, Put it in the second 2 In the object created by step .

 var s = [0, 2, 3, 4, 4, 0, 2, 'tt', 0, 0]; // Test array 
for (var i = 0, o = {}, tmp = [], count = 0, l = s.length; i < l; i++) {
if (o[s[i]]) {
count++;// repeat +1
} else {
o[s[i]] = 1;// Do not set properties repeatedly
tmp.push(s[i])// Add a new array
}}
alert(count);alert(tmp)

14. Event delegation .

Using the principle of bubbling , Add event to parent , Trigger execution effect . Using event delegation technology allows you to avoid adding event listeners to specific nodes ; contrary , Event listeners are added to their parent elements . Event listeners analyze events bubbling up from child elements , Find out which child element's event is .

15. Scope chain .

When code is executed in an environment , Will create a scope chain of variable objects (scope chain). Scope chain usage , Is to ensure orderly access to all variables and functions that the execution environment has access to . Front end of scope chain , It is always the variable object of the environment in which the current code is executed . If this environment is a function , Then its active object is taken as a variable object .

Each function has its own execution environment , When execution flows into a function , The function environment is pushed into an environment stack , And after the function executes , The stack pops up its environment , Return control to the previous execution environment , This stack is the scope chain .

When a function is executed , The execution environment for the function is created ( Call object ), And put the object at the beginning of the linked list , Then link the calling object of the parent function after , Finally, the global object .

16. Closure .

Closures are functions that can read internal variables of other functions . Because in Javascript In language , Only subfunctions inside a function can read local variables , So we can simply understand closures as " A function defined inside a function ". therefore , In essence , A closure is a bridge connecting the inside and outside of a function . Closures can be used in many places . It has two great uses , One is to read the variables inside the function , The other is to keep the values of these variables in memory .

1) Because closures keep variables in functions in memory , Memory consumption is high , So you can't abuse closures , Otherwise it will cause performance problems , stay IE May cause memory leaks in . The solution is , Before exiting the function , Delete all unused local variables .

2) The closure will be outside the parent function , Change the value of the internal variable of the parent function . therefore , If you take the parent function as an object (object) Use , Use closures as its common method (Public Method), Treat internal variables as their private properties (private value), Be careful at this time , Don't change the value of the internal variable of the parent function .

17. How to prevent event bubbling and default Events .

// If an event object is provided , Then this is a non IE browser 
if ( e && e.stopPropagation ) {
e.stopPropagation(); // So it supports W3C Of stopPropagation() Method
} else {
window.event.cancelBubble = true; // otherwise , We need to use IE To cancel the event bubble
return false;
}
// If an event object is provided , Then this is a non IE browser
if ( e && e.preventDefault ) {
e.preventDefault(); // Prevent default browser actions (W3C)
} else {
window.event.returnValue = false; //IE How to prevent the default action of the functor in
return false;
}

18.javascript The same origin strategy .

A script can only read the properties of windows and documents from the same source , The same source here refers to the hostname 、 The combination of protocol and port number

19.JS Sorting algorithm .

var sort = {
debug: function(str) {
if (window.console && window.console.log) {
console.log(str);
}
},
swap: function(arr, index1, index2) { // Array data exchange
var temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
},
bubbleSort: function(arr) { // Bubble sort
this.debug(" Bubble sort before:" + arr);
var len = arr.length;
for (var outer = 0; outer < len - 1; outer++) { // The number of rounds compared
for (var inner = 0; inner < len - outer - 1; inner++) { // The number of comparisons per round
if (arr[inner] > arr[inner + 1]) {
this.swap(arr, inner, inner + 1)
}
}
this.debug(" The first " + (outer + 1) + " After wheel :" + arr);
}
this.debug(" Bubble sort after:" + arr);
},
selectionSort: function(arr) { // Selection sort
this.debug(" Selection sort before:" + arr);
var min, len = arr.length;
for (var outer = 0; outer < len - 1; outer++) {
min = outer;
// Compare the smallest project with the second outer The remaining array items after , To find smaller items
for (var inner = outer + 1; inner < len; inner++) {
if (arr[inner] < arr[min]) {
min = inner;
this.debug("min--" + min);
}
}
this.swap(arr, outer, min);
this.debug(" The first " + (outer + 1) + " After wheel :" + arr);
}
this.debug(" Selection sort after:" + arr);
},
insertionSort: function(arr) { // Insertion sort
this.debug(" Insertion sort before:" + arr);
var temp, inner, len = arr.length;
for (var outer = 1; outer < len; outer++) {
temp = arr[outer];
inner = outer;
while (inner > 0 && arr[inner - 1] >= temp) {
arr[inner] = arr[inner - 1];
--inner;
}
arr[inner] = temp;
}
this.debug(" Insertion sort after:" + arr);
},
shellSort: function(arr) { // Shell Sort
this.debug(" Shell Sort before:" + arr);
var gaps = [5, 3, 1],
temp;
for (var g = 0; g < gaps.length; g++) {
for (var i = gaps[g]; i < arr.length; i++) {
temp = arr[i];
for (var j = i; j >= gaps[g] && arr[j - gaps[g]] > temp; j -= gaps[g]) {
arr[j] = arr[j - gaps[g]];
}
arr[j] = temp;
}
}
this.debug(" Shell Sort after:" + arr);
},
shellSortDynamic: function(arr) { // Dynamically calculate the hill ordering of interval sequences
this.debug(" Dynamically calculate the hill ordering of interval sequences before:" + arr);
var N = arr.length,
h = 1;
while (h < N / 3) {
h = 3 * h + 1;
}
while (h >= 1) {
for (var i = h; i < N; i++) {
for (var j = i; j >= h && arr[j] < arr[j - h]; j -= h) {
this.swap(arr, j, j - h);
}
}
h = (h - 1) / 3;
}
this.debug(" Dynamically calculate the hill ordering of interval sequences after:" + arr);
},
mergeSort: function(arr) { // Merge sort
this.debug(" Merge sort before:" + arr);
var len = arr.length,
step = 1,
left,
right;
var mergeArray = function(arr, startLeft, stopLeft, startRight, stopRight) {
var rightArr = new Array(stopRight - startRight + 1),
leftArr = new Array(stopLeft - startLeft + 1),
k = startRight,
m = 0,
n = 0;
for (var i = 0; i < (rightArr.length - 1); ++i) {
rightArr[i] = arr[k];
++k;
}
k = startLeft;
for (var i = 0; i < (leftArr.length - 1); ++i) {
leftArr[i] = arr[k];
++k;
}
rightArr[rightArr.length - 1] = Infinity; // Sentinels are worth
leftArr[leftArr.length - 1] = Infinity; // Sentinels are worth
for (var k = startLeft; k < stopRight; ++k) {
if (leftArr[m] <= rightArr[n]) {
arr[k] = leftArr[m];
m++;
} else {
arr[k] = rightArr[n];
n++
}
}
}
if (len < 2) {
return;
}
while (step < len) {
left = 0;
right = step;
while (right + step <= len) {
mergeArray(arr, left, left + step, right, right + step);
left = right + step;
right = left + step;
}
if (right < len) {
mergeArray(arr, left, left + step, right, len);
}
step *= 2;
}
this.debug(" Merge sort after:" + arr);
},
quickSort: function(arr) { // Quick sort
this.debug(" Quick sort before:" + arr);
var _quickSort = function(arr) {
var len = arr.length,
lesser = [],
greater = [],
pivot,
meCall = arguments.callee;
if (len == 0) {
return [];
}
pivot = arr[0];
for (var i = 1; i < len; i++) {
if (arr[i] < pivot) {
lesser.push(arr[i])
} else {
greater.push(arr[i])
}
}
return meCall(lesser).concat(pivot, meCall(greater));
}
this.debug(" Quick sort after:" + _quickSort(arr));
return _quickSort(arr);
}
}
var search = {
linearSearch: function(arr, data) { // Linear search
for (var i = 0; i < arr.length; i++) {
if (arr[i] == data) {
return i;
}
}
return -1;
},
binarySearch: function(arr, data) { // Two points search For ordered linear structures
var lowerBound = 0,
upperBound = arr.length - 1,
mid;
while (lowerBound <= upperBound) {
mid = Math.floor((lowerBound + upperBound) / 2);
if (arr[mid] < data) {
lowerBound = mid + 1;
} else if (arr[mid] > data) {
upperBound = mid - 1;
} else {
return mid;
}
return -1;
}
}
}
var tempArr = [3, 6, 4, 2, 11, 10, 5];
//sort.bubbleSort(tempArr);
//sort.selectionSort(tempArr);
//sort.insertionSort(tempArr);
//sort.shellSort(tempArr);
//sort.shellSortDynamic(tempArr);
//sort.mergeSort(tempArr);
//sort.quickSort(tempArr);

20. explain jsonp Principle , And why not really ajax.

1、Ajax The problem of cross domain unauthorized access exists in direct request for ordinary files , Whether you're a static page 、 Dynamic web pages 、web service 、WCF, As long as it's a cross domain request , No way. ;

2、 however Web Call on page js Files are not affected by whether they are cross domain or not ( All owned "src" The tags of this attribute have the ability of cross domain , such as <script>、<img>、<iframe>);

3、 So we can judge , If you want to pass pure web End (ActiveX Control 、 Server agent 、 Belonging to the future HTML5 And Websocket It doesn't count ) Cross domain access to data is only possible , That's trying to load data into a remote server js In the format file , For client call and further processing ;

4、 There's one called JSON The pure character data format of can describe complex data succinctly , What is more wonderful is that JSON Has also been js Native support , So in the client side, you can almost handle the data in this format as you like ;

5、web The client is as like as two peas. , To call the dynamically generated js Format file ( General with JSON For the suffix ), Obvious , Why the server needs to generate dynamically JSON file , The purpose is to load the data required by the client .

6、 Client in right JSON After successful file call , And you get the data you need , What's left is to process and present according to your own needs , This way of getting remote data looks very similar AJAX, But it's not the same .

7、 For the convenience of the client , An informal transmission protocol is gradually formed , People call it JSONP, A key point of the protocol is to allow users to pass a callback Parameter to server , Then when the server returns data, it will callback Parameters are wrapped as function names JSON data , In this way, the client can customize its own functions to automatically process the returned data .

1、ajax and jsonp These two technologies are in the call mode “ look ” It's like , The same purpose , It's all about asking for one url, Then process the data returned by the server , therefore jquery and ext And so on jsonp As ajax A form of ;

2、 but ajax and jsonp Actually, it's different in nature .ajax At the heart of it is through XmlHttpRequest Get content not on this page , and jsonp The core is dynamic addition <script> Tag to call the server provided js Script .

3、 So , Actually ajax And jsonp The difference is not whether it is cross domain ,ajax Cross domain can be realized by server agent ,jsonp It does not exclude the data acquisition in the same domain .

4、 And that is ,jsonp It's a way or an optional agreement , Like ajax equally , It doesn't have to be used json Format to transfer data , If you will , String is OK , But it's not good for use jsonp Provide public services .

To make a long story short ,jsonp No ajax A special case of , Even if the jquery And so on. jsonp Packaged in ajax, It can't change a little !

21.CSS Preprocessing .

Css The preprocessor defines a new language that will Css Generate files as targets , Then developers just need to code in this language . Preprocessors are usually browser compatible , Variable , Structure and other functions , The code is simpler and easier to maintain .

The two popular ones are Sass and Less, Others are Stylus 、Dtcss etc. . You don't have to out Did you? , It depends ?LESS CSS It's a powerful tool , It makes up for css No variables 、 Can't calculate, etc “ Birth defects ”.

22. Prototype chain .

The prototype object of the function constructor The default point is to the function itself , Prototype objects have prototype properties , In order to implement inheritance , There's also a prototype chain pointer proto, This pointer points to the prototype object one level up , The structure of the prototype object on the upper layer is still similar , Use it like this proto Point all the way to Object On the prototype object , and Object The prototype object of Object.proto = null Represents the top of the prototype chain , And so it became javascript The prototype chain of inheritance , It also explains why all the javascript Objects all have Object Basic approach .

23. You know, attribute and property The difference? .

1. Definition

Property: attribute , be-all HTML All elements are made of HTMLElement Type said ,HTMLElement The type directly inherits from Element And added some properties , The added attributes correspond to each HTML The elements all have the following 5 A standard feature :id,title,lang,dir,className.DOM A node is an object , therefore , He can be with the others JavaScript Object to add custom properties and methods .property The value of can be any data type , Case sensitive , Self defined property Will not appear in html In the code , There is only js in .

Attribute: characteristic , The difference in property,attribute It can only be a string , Case insensitive , Appear in the innerHTML in , Through the class array attributes You can list all of them attribute.

2. Similarities

The standard DOM properties And attributes It's synchronous . Recognized ( Non custom ) Features are added as attributes to DOM In the object . Such as ,id,align,style etc. , This is the time to operate property Or using operational features DOM The method is as follows getAttribute() You can manipulate properties . But pass it on to getAttribute() The property name of is the same as the actual property name . So for class When you get the property value of “class”.

3. The difference

For the operation of some standard features ,getAttribute And the dot (.) The values obtained are different . Such as href,src,value,style,onclick And so on .

href:getAttribute What you get is href The real value of , And the point number is complete url, There are browser differences .

4. Differences in browser compatibility

stay IE<9 In the browser of , You can use dot and getAttribute Access custom properties between each other .

IE<8( Include IE8 Species IE7 Compatibility mode ),property and attribute identical . because attribute Case insensitive , under these circumstances , use getAttribute When accessing features , The browser selects the value that first appears .

24. Explain JavaScript in this How it works .

In the function :this  It's usually an implicit parameter .

Outside the function ( In the top-level scope ): In the browser this  The global object ; stay Node.js I mean modules (module) Export of (exports).

Pass on to eval() String in : If eval() It's called directly ,this  Refers to the current object ; If eval() Is called indirectly ,this  It means global objects .

25. Explain how archetypal inheritance works ?

When looking up the properties of an object ,JavaScript Will traverse the prototype chain up , Until the property with the given name is found .

26.AMD vs CommonJS?

CommonJS yes javascript A specification for modular programming , Mainly in the server-side modular specification , A single file is a module . Each module is a separate scope , in other words , Variables defined within the module , Cannot be read by other modules , Unless defined as global Object properties .

CommonJS The load module is synchronous , Only load complete , To perform the following operations , The main reason is that the programming module files of the server exist in the local hard disk , So it loads faster .

AMD yes "Asynchronous Module Definition" Abbreviation , It means " Asynchronous module definition ". Loading modules asynchronously , The loading of a module does not affect the execution of the statements following it . All statements that depend on this module , Are defined in a callback function , Wait until the load is complete , This callback function will run .

27.AMD vs CMD?

1. For dependent modules ,AMD yes Advance execution ,CMD yes Delay the . however RequireJS from 2.0 Start , It can also delay execution ( According to the way of writing , Different ways of handling ).CMD To promote as lazy as possible.
2. CMD To promote Rely on proximity ,AMD To promote Rely on the pre - .

3. AMD Of API The default is one when more than one is used ,CMD Of API Strictly distinguish between , Promote single responsibility . such as AMD in ,require Divide the whole situation require And parts require, All call require.CMD in , There is no overall situation require, But according to the completeness of the module system , Provide seajs.use To load and start the module system .CMD in , Every API It's all simple and pure .

4. There are also some differences in details , See the definition of this specification , Not much .

28. Expand JavaScript Built-in objects ?

Generally speaking , It is generally accepted in the industry that they hold the latter view , But if you think your code is controllable , Extend the built-in objects prototype It's a very convenient way (prototype There's a lot of this in the library ), In particular, after expansion, the original object instance is taken as this Context call ,api It's beautiful and direct , Otherwise , Pass the object instance as a parameter to the method , It doesn't look so “ object-oriented ” 了 , Of course , This problem can be solved by encapsulating the original object with a layer wrap To solve , such as jquery Packaging , Can be in $ Instantiated dom Object , And you can chain call .

29. How to get from the browser's URL Get the query string parameter from the ?

// Regular
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
// obtain URl Parameters
function parseUrl(url) {
var parse = url.substring(url.indexOf("?") + 1),
params = parse.split("&"),
len = params.length,
item = [],
param = {};
for (var i = 0; i < len; i++) {
item = params[i].split("=");
param[item[0]] = item[1];
}
return param;
}
// demo:
parseUrl("www.baidu.com/js?name=baidu&age=22&page=3")
// result
{name: "haorooms", age: "21", page: "2"}

30. What is? "use strict"; ? What are the advantages and disadvantages of using it ?

Strict mode

1. eliminate Javascript Some unreasonable grammar 、 Not rigorous , Reduce some weird behavior ;

2. Eliminate some insecurity of code running , Ensure the safety of code operation ;

3. Improve compiler efficiency , Increase running speed ;

4. For future new versions of Javascript Pave the way .

shortcoming :

Now the JS Will be compressed , Some documents use a strict pattern , And others don't . At this time, these documents were originally strict models , By merge after , This string is in the middle of the file , Not only are strict patterns not indicated , Instead, bytes are wasted after compression .

31. Common compatibility issues ?

png24 The picture of bit is in iE6 Background appears on Browser , The solution is to PNG8.

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

IE6 Double margins bug: Block attribute label float after , There's another wild one margin Under the circumstances , stay ie6 Show margin Bigger than the setting .

float ie Double the distance #box{ float:left; width:10px; margin:0 0 0 100px;}

In this case IE Will produce 20px Distance of , The solution is float Add... To the label style control ——_display:inline; Convert it to inline properties .(_ This symbol only has ie6 identifies )

The way of progressive recognition , Gradually exclude parts from the whole .

First , Clever use “\9” This sign , take IE The Tourer is separated from all situations .

next , Again using “+” take IE8 and IE7、IE6 Separate from , such IE8 Has independently identified .

css

.bb{

/* All identification */

. /*IE6、7、8 distinguish */

+/*IE6、7 distinguish */

_/*IE6 distinguish */

}

IE Next , You can use the method of getting general properties to get custom properties ,

You can also use getAttribute() Get custom properties ;

Firefox Next , Only use getAttribute() Get custom properties .

resolvent : To pass through getAttribute() Get custom properties .

IE Next ,even Objects have x,y attribute , But no pageX,pageY attribute ;

Firefox Next ,event Objects have pageX,pageY attribute , But no x,y attribute .

resolvent :( conditional comments ) The disadvantage is that IE There may be additional HTTP Number of requests .

Chrome By default, it will be less than 12px The text of is forced to follow 12px Show ,

By joining CSS attribute -webkit-text-size-adjust: none; solve .

After the hyperlink visit hover The pattern doesn't show up The hyperlink style visited by the click no longer has hover and active The solution is to change CSS The order in which attributes are arranged :

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

32.html5 What's new 、 Removed those elements ? How to deal with it HTML5 Browser compatibility issues with new tags ? How to distinguish between HTML and HTML5??

HTML5 Not now SGML Subset , Mainly about images , Location , Storage , Increase of multi task and other functions .

painting canvas

For media playback video and audio Elements

Local offline storage localStorage Long term data storage , Data will not be lost after browser is closed ;

sessionStorage Data is automatically deleted when the browser is closed

Semantic better content elements , such as article、footer、header、nav、section

The form controls ,calendar、date、time、email、url、search

New technology webworker, websockt, Geolocation

Removed elements

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

Elements that have a negative impact on availability :frame,frameset,noframes;

Support HTML5 The new label :

IE8/IE7/IE6 Supported by document.createElement Method generated tags ,

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

Browser support for new tags after , You also need to add the default style of the label :

Of course, the best way is to use mature framework directly 、 The most used is html5shim frame

<!--[if lt IE 9]>

<script> src="http://html5shim.googlecode.com/svn/trunk/html5.js"</script>

<![endif]-->

How to distinguish between : DOCTYPE Statement \ New structural elements \ Functional elements

33. What should the front end pay attention to SEO?

  1. reasonable title、description、keywords: The search reduces the weight of the three items one by one ,title Emphasize the key points , Important keywords should not appear more than 2 Time , And it depends on the front , Different pages title Make a difference ;description Summarize the content of the page , The length is right , Don't pile up key words too much , Different pages description Somewhat different ;keywords List the key words
  2. Semantically HTML Code , accord with W3C standard : Semantic code makes it easy for search engines to understand web pages
  3. Important content HTML Code at the top : Search engine grabs HTML The order is from top to bottom , Some search engines have restrictions on the length of crawling , Make sure important content is captured
  4. Don't use the important content js Output : Crawlers don't execute js Get content
  5. To use less iframe: Search engines don't grab iframe The content in
  6. Non decorative pictures must be added with alt
  7. Speed up your website : Website speed is an important index of search engine ranking

34.offsetWidth/offsetHeight,clientWidth/clientHeight And scrollWidth/scrollHeight The difference between ?

offsetWidth/offsetHeight The return value contains content + padding + border, Effect and e.getBoundingClientRect() identical

clientWidth/clientHeight The return value contains only content + padding, If there is a scroll bar , also No scrollbars

scrollWidth/scrollHeight The return value contains content + padding + The size of the overflow content

 

Maybe you need something practical -Web More related articles on the front-end pen test

  1. 2015 tencent web Front end written test questions

      1 Please implement , Click on any label on the page ,alert The name of the label .( Pay attention to compatibility ) 2 Please point out the performance issues of the code , And optimized . var info=" Tencent paipai.com (www.paipai.com) yes ...

  2. tencent 2013 Pen test —web Front end written test questions ( Practice your hand )

    Problem description (web Front end development additional questions 1): Write a javascript A function of url It is related to the page javascript.location Object similar entity objects , Such as :url :'http://www.qq.co ...

  3. web Front end written test questions

    1,  Determine whether a string is composed like this , The first must be the letters , It can be followed by letters . Numbers . Underline , The total length of 5-20 var reg = /^[a-zA-Z][a-zA-Z_0-9]{4,19}$/; reg.test ...

  4. tencent web Front end written questions and personal answers

    Every question has an answer , Most of the answers are right . Short answer 1.js in “5”+4=? answer :54 2.js in void(0)=? answer :undefined 3.js in NaN*4=? answer :NaN 4.js in null* ...

  5. web Summary of the front-end written test questions

    em and rem The difference between : The default font height for browsers is 16px,1em=16px: You can set and adjust the size yourself , And the default size of the text in the integrated parent container . rem yes CSS3 New properties in , The default is the size of the text size , The difference is that it sets ...

  6. gold s Office software web Front end written test questions

    1. var arr = []; arr['a'] = 1; console.log(arr.length); // A arr['4'] = 2; console.log(arr.length); ...

  7. web Front end Interview Questions Summary ---html piece

    HTML Doctype effect ? What's the difference between standard mode and compatible mode ? (1).<!DOCTYPE> The statement is at HTML The first line in the document , be in <html> Before the label . Tell browser's parser ...

  8. web Front end Interview Questions Summary --- other

    Other questions What's the original workflow of the company , How to work with others ? How to promote the cooperation between departments ? The more difficult technical problem you have encountered is ? How did you solve ? Design patterns Know what is singleton, factory, strategy ...

  9. web Front end Interview Questions Summary ---css piece

    CSS Introduce the standard CSS Box model of ? Low version IE What's the difference between the box model of ? (1) There are two kinds of , IE Box model .W3C Box model : (2) The box model : Content (content). fill (padding). The border (m ...

Random recommendation

  1. Use NPOI Reading and writing Excel、Word

    NPOI yes  POI  Project .NET edition .POI It's an open source Java Reading and writing Excel.WORD Wait for Microsoft OLE2 Items for component documents . Use NPOI You can install it without installing it Office Or on the machine of the corresponding environment ...

  2. MvcPager summary MvcPager Pagination example — standard Ajax Pagination Yes SEO Optimized ajax Pagination ( Support asp.net mvc)

    This example demonstrates how to use MvcPager The most basic Ajax Paging mode . Use AjaxHelper Of Pager Extend the method to achieve Ajax Pagination , Use Ajax In paging mode , At least... Must be specified MvcAjaxOptions Of Upda ...

  3. WPS Project number problem

    problem : The document needs to be numbered as follows : 1.( title 1) 1.1( title 2) 1.1.1( title 3) 1.2 1.2.1 2.( title 1) 2.1( title 2) 2.1.1( title 3) 2.2 2.2.1 Method 1 : First step , open ...

  4. The suffix array ---Musical Theme

    POJ   1743 Description A musical melody is represented as a sequence of N (1<=N<=20000)notes t ...

  5. 2dx Chinese code scrambling

    There's one in our code bug In order to be compatible with the previously compatible planning guide tool The table guide tool exports excel All of them are ansi Of For compatibility, it can only be manually changed to utf 8 nothing bom Format I got tired of planning later Let's deal with this in the program section I've studied it. OK ...

  6. jquery $.trim() Method introduction

    $.trim(str) Is to remove the beginning and end of the string space $.trim(str) return :string: explain : Remove the leading and trailing spaces of the string . Example : Let's start with an error code : <input type="text ...

  7. ESFramework Development Manual (07) -- Off line and heartbeat mechanism ( turn )

    Although we've already done that ESFramework Develop the infrastructure you need to master , But not enough . Want to make better use of ESFramework This weapon , Some background knowledge is something we have to understand . Just like the heartbeat mechanism described in this article , In the severe In ...

  8. MySQL The function of time in NOW() and SYSDATE() The difference between

    mysql The date function is more commonly used in . There are mainly NOW() and SYSDATE() Two kinds of , Although they all indicate the current time , But there's a little difference in use . NOW() It takes the start time of the statement ,SYSDATE() Take the dynamic real-time time . ...

  9. Vue Communication between parent and child components

    Components are Vue One of the most important parts of the knowledge system , Due to the different scopes of parent-child components , Can't operate the data of the other party directly . The data transmission between them is carried out through the intermediate medium , The parent component passes values to the child component through props attribute , The child component passes values to the parent component ...

  10. shell Programming -test command ( 7、 ... and )

    test Commands are often used to check whether certain conditions hold . The numerical test -eq: Check whether two numbers are equal , Equal return true -ne: Check whether two numbers are equal , Unequal return true -gt: Check if the number on the left is greater than the number on the right , Yes, go back to true - ...