search
HomeWeb Front-endJS Tutorial96 basic front-end JS interview questions (including answers)

96 basic front-end JS interview questions (including answers)

Jun 28, 2020 am 09:40 AM
javascriptFront-end development

[Related recommendations: Front-end interview questions

1. Several basic data Type? Complex data type? Value type and reference data type? Stack data structure?

Basic data types: Undefined, Null, Boolean, Number, String
Value type: Numeric, Boolean, null, undefined.
Reference type: object, array, function.
Stack data structure: It is a collection that supports last-in-first-out (LIFO), that is, the data inserted later is taken out first!
The following methods are provided in the js array to make it easy for us to implement the stack :
shift: Delete the first element from the array and return the value of this element.
unshift: Add one or more elements to the beginning of the array and return the new length
push: Add elements to the end of the array and return the new length
pop: Remove the last element from the array Removes an element and returns the value of this element.

2. Declaring function promotion? What is the difference between declaring a variable and declaring a function?

(1) Variable declaration promotion: variable declaration before entering The execution context is complete.
As long as a variable is declared in the code, no matter where it is declared, the js engine will place its declaration at the top of the scope;

(2) Function declaration promotion: execution The function declaration is read before the code, which means that the function declaration can be placed after the statement that calls it.
As long as the function is declared in the code, no matter where it is declared, the js engine will place its declaration at the top of the scope;

(3) Variable or function declaration: Function declarations override variable declarations, but not variable assignments.
The same name identifies a, that is, there is a variable declaration var a, and a function declaration function a() {}. Regardless of the order of the two declarations, the function declaration will overwrite the variable declaration, that is, the value of a at this time is the declared function function a() {}. Note: If a is initialized at the same time as the variable is declared, or a is assigned a value later, the value of a at this time is the value of the variable. eg: var a; var c = 1; a = 1; function a() { return true; } console.log(a);

3. Determine the data type?

The types returned by typeof are all in the form of strings, which can be used to determine the type of function; it is more convenient to determine objects of type other than Object.
Method to determine known object type: instanceof, which must be followed by the object type, and the case cannot be wrong. This method is suitable for some conditional selection or branching.

4. Asynchronous programming?

Method 1: Callback function. The advantage is that it is simple, easy to understand and deploy. The disadvantage is that it is not conducive to reading and maintaining the code. The various parts are highly coupled (Coupling), and the process will be very complicated. Confusing, and only one callback function can be specified per task.

Method 2: Time monitoring, multiple events can be bound, each event can specify multiple callback functions, and can be "decoupled" (Decoupling), which is conducive to modularization. The disadvantage is that the entire program has to become event-driven, and the running process will become very unclear.

Method 3: Publish/subscribe, similar in nature to "event listening", but obviously better than the latter.

Method 4: Promises object is a specification proposed by the CommonJS working group to provide a unified interface for asynchronous programming.
Simply put, the idea is that each asynchronous task returns a Promise object, which has a then method that allows a callback function to be specified.

5. Event flow? Event capture? Events bubbling up?

Event flow: The order in which events are received from the page. That is to say, when an event occurs, the propagation process of this event is the event flow.

The event stream in IE is called event bubbling; event bubbling: the event is initially received by the most specific element, and then propagated upwards to less specific nodes (documents). For HTML, when an element generates an event, it will pass the event to its parent element. After the parent element receives it, it will continue to pass it to its upper-level element, and then it will be propagated to the document. Object (Personally tested the current browser to window object, only IE8 and below are not like this

Event capture is that less specific elements should receive events earlier, and the most specific nodes should receive events last. Their intention is to capture the event before it reaches the target; that is, it is exactly the opposite of the bubbling process. Taking the click event of HTML as an example, the document object (DOM-level specification requires that the propagation starts from the document, but current browsers start from the document). The window object (beginning with the window object) first receives the click event, and then the event propagates downward along the DOM tree until it reaches the actual target of the event;

6. How to clear a timer?

window.clearInterval();
window.clearTimeout();

7. How to add a dom object to the body? What is the difference between innerHTML and innerText?

body.appendChild(dom element);
innerHTML: All content from the starting position to the ending position of the object, including Html tags.
innerText: Content from the starting position to the ending position, but it removes the Html tag
Briefly describe the five window objects and attributes respectively

Member objects
window.event window.document window .history
window.screen window.navigator window.external
The properties of the Window object are as follows:
window //Window itself
window.self //Reference this window window=window.self
window.name //Name the window
window.defaultStatus //Set the window status bar information
window.location //URL address, equipped with this attribute, you can open a new page

8. Data persistence technology (ajax)? Briefly describe the ajax process

1) Client generates js events
2) Create XMLHttpRequest object
3) Respond to XMLHttpRequest Configure
4) Send an asynchronous request through the AJAX engine
5) The server receives the request and processes the request, returning html or xml content
6)XML calls a callback() to process the response content
7) Partial page refresh

9. Callback function?

The callback function is a function called through a function pointer. If you pass a function pointer (address) as a parameter to another function, and when this pointer is used to call the function it points to, we say it is a callback function. The callback function is not called directly by the implementer of the function, but is called by another party when a specific event or condition occurs to respond to the event or condition.

10. What is a closure?* What is the difference between Stack Overflow and Stack Overflow? Memory leak? What operations can cause memory leaks? How to prevent memory leaks?

Closure: It is a function that can read the internal variables of other functions.
Stack overflow: regardless of the size of the local data block allocated in the stack, too much data is written to the data block, causing the data to go out of bounds and overwriting other data. Often happens with recursion.
Memory leak refers to: using dynamic storage to allocate function memory space, which is not released after use, resulting in the memory unit being occupied all the time. until the program ends. Refers to any object that survives after you no longer own or need it.

Causing memory leaks:
If the first parameter of setTimeout uses a string instead of a function, it will cause a memory leak.
Closure, console log, loop (when two objects refer to each other and retain each other, a loop will be generated)
Prevent memory leaks:
1. Do not bind events dynamically;
2. Do not bind events to DOM that is dynamically added or dynamically removed. Use events to bubble up in the parent container to listen for events;
3. If you want to violate the above principles, you must provide a destroy method to ensure that the DOM is removed. Backbone events have also been removed. You can refer to Backbone's source code for this, which is better;
4. Singletonization, less DOM creation and less event binding.

11. How to interact with data in daily work? How to develop if the background does not provide data? What should I do if the mock data does not agree with the format returned by the background?

The backend writes interface documents, provides data interface implementation, and the frontend realizes data interaction through ajax access;
If there is no data, look for the backend to provide static data or define mock data by yourself;
The returned data is not uniform When writing a mapping file to map the data.

12 Briefly describe the ajax execution process

基本步骤:var xhr =null;//创建对象 
if(window.XMLHttpRequest){
       xhr = new XMLHttpRequest();}else{
       xhr = new ActiveXObject("Microsoft.XMLHTTP");}xhr.open(“方式”,”地址”,”标志位”);//初始化请求 
   xhr.setRequestHeader(“”,””);//设置http头信息 
xhr.onreadystatechange =function(){}//指定回调函数 
xhr.send();//发送请求

13. Self-executing function? What scenarios is it used for? Benefits?

Self-executing function: 1. Declare an anonymous function 2. Call the anonymous function immediately.
Function: Create an independent scope.

Benefits: Prevent variables from spreading to the global world to avoid conflicts with various js libraries. Isolate the scope to avoid contamination, or truncate the scope chain to avoid closures that prevent reference variables from being released. Utilize the immediate execution feature to return the required business functions or objects, avoiding the need to deal with conditional judgments every time

Scenarios: generally used in scenarios such as frameworks and plug-ins

14.html and What is the difference between xhtml?

HTML is a basic WEB web page design language, and XHTML is a markup language based on XML.
1.XHTML elements must be nested correctly.
2.XHTML elements must be closed.
3. Tag names must use lowercase letters.
4. Empty tags must also be closed.
5.XHTML documents must have a root element.

15. What is a constructor? What is the difference from ordinary functions?

构造函数:是一种特殊的方法、主要用来创建对象时初始化对象,总与new运算符一起使用,创建对象的语句中构造函数的函数名必须与类名完全相同。
与普通函数相比只能由new关键字调用,构造函数是类的标示

16. 通过new创建一个对象的时候,函数内部有哪些改变

function Person(){}Person.prototype.friend = [];Person.prototype.name = '';// var a = new Person();// a.friend[0] = '王琦';// a.name = '程娇';// var b = new Person();// b.friend?// b.name?
1、创建一个空对象,并且 this 变量引用该对象,同时还继承了该函数的原型。
2、属性和方法被加入到 this 引用的对象中。
3、新创建的对象由 this 所引用,并且最后隐式的返回 this 。

17.事件委托?有什么好处?

(1)利用冒泡的原理,把事件加到父级上,触发执行效果
(2)好处:新添加的元素还会有之前的事件;提高性能。

18.window.onload ==? DOMContentLoaded ?

一般情况下,DOMContentLoaded事件要在window.onload之前执行,当DOM树构建完成的时候就会执行DOMContentLoaded事件,而window.onload是在页面载入完成的时候,才执行,这其中包括图片等元素。大多数时候我们只是想在DOM树构建完成后,绑定事件到元素,我们并不需要图片元素,加上有时候加载外域图片的速度非常缓慢。

19.节点类型?判断当前节点类型?

1. 元素节点                        
2. 属性节点                        
3. 文本节点                        
8. 注释节点                        
9. 文档节点                        
通过nodeObject.nodeType判断节点类型:其中,nodeObject 为DOM节点(节点对象)。该属性返回以数字表示的节点类型,例如,元素节点返回 1,属性节点返回 2 。

20.如何合并两个数组?数组删除一个元素?

//三种方法。 (1)var arr1=[1,2,3];
               var arr2=[4,5,6];
               arr1 = arr1.concat(arr2);
               console.log(arr1); 
 (2)var arr1=[1,2,3];
               var arr2=[4,5,6];
               Array.prototype.push.apply(arr1,arr2);
               console.log(arr1);
 (3)var arr1=[1,2,3];
               var arr2=[4,5,6];
               for (var i=0; i <p><strong>21.强制转换 显式转换 隐式转换?</strong></p><pre class="brush:php;toolbar:false">//强制类型转换:
Boolean(0)                // => false - 零
           Boolean(new object())   // => true - 对象
               Number(undefined)       // =>   NaN
               Number(null)              // => 0
               String(null)              // => "null"
parseInt( )
parseFloat( )
JSON.parse( )
JSON.stringify ( )
隐式类型转换:
在使用算术运算符时,运算符两边的数据类型可以是任意的,比如,一个字符串可以和数字相加。之所以不同的数据类型之间可以做运算,是因为JavaScript引擎在运算之前会悄悄的把他们进行了隐式类型转换的
(例如:x+""         //等价于String(x)
              +x                 //等价于Number(x)
              x-0         //同上
              !!x         //等价于Boolean(x),是双叹号)

显式转换:
如果程序要求一定要将某一类型的数据转换为另一种类型,则可以利用强制类型转换运算符进行转换,这种强制转换过程称为显示转换。
显示转换是你定义让这个值类型转换成你要用的值类型,是底到高的转换。例 int 到float就可以直接转,int i=5,想把他转换成char类型,就用显式转换(char)i

22. Jq中如何实现多库并存?

Noconfict 多库共存就是“$ ”符号的冲突。

方法一: 利用jQuery的实用函数$.noConflict();这个函数归还$的名称控制权给另一个库,因此可以在页面上使用其他库。这时,我们可以用"jQuery "这个名称调用jQuery的功能。 $.noConflict();  
jQuery('#id').hide();    
.....
//或者给jQuery一个别名  
var $j=jQuery  
$j('#id').hide();    
.....

方法二: (function($){})(jQuery)

方法三: jQuery(function($){})
通过传递一个函数作为jQuery的参数,因此把这个函数声明为就绪函数。 我们声明$为就绪函数的参数,因为jQuery总是吧jQuery对象的引用作为第一个参数传递,所以就保证了函数的执行。

23.Jq中get和eq有什么区别?

get() :取得其中一个匹配的元素。num表示取得第几个匹配的元素,get多针对集合元素,返回的是DOM对象组成的数组 eq():获取第N个元素,下标都是从0开始,返回的是一个JQuery对象

24.如何通过原生js 判断一个元素当前是显示还是隐藏状态?

if( document.getElementById("div").css("display")==='none')
if( document.getElementById("div").css("display")==='block')
$("#div").is(":hidden"); // 判断是否隐藏
$("#div").is(":visible")

25.Jq如何判断元素显示隐藏?

//第一种:使用CSS属性 
var display =$('#id').css('display'); 
if(display == 'none'){    alert("我是隐藏的!"); }
//第二种:使用jquery内置选择器 
<div> <p>仅仅是测试所用</p> </div>
if($("#test").is(":hidden")){        
	$("#test").show();    
	//如果元素为隐藏,则将它显现 
}else{       
	$("#test").hide();     
	//如果元素为显现,则将其隐藏 
}
//第三种:jQuery判断元素是否显示 是否隐藏
var node=$('#id');
if(node.is(':hidden')){  //如果node是隐藏的则显示node元素,否则隐藏
  node.show(); 
}else{
  node.hide();
}

26.移动端上什么是点击穿透?

点击穿透现象有3种:
点击穿透问题:点击蒙层(mask)上的关闭按钮,蒙层消失后发现触发了按钮下面元素的click事件跨页面点击穿透问题:如果按钮下面恰好是一个有href属性的a标签,那么页面就会发生跳转另一种跨页面点击穿透问题:这次没有mask了,直接点击页内按钮跳转至新页,然后发现新页面中对应位置元素的click事件被触发了

解决方案:
1、只用touch
最简单的解决方案,完美解决点击穿透问题
把页面内所有click全部换成touch事件( touchstart 、’touchend’、’tap’)

2、只用click
下下策,因为会带来300ms延迟,页面内任何一个自定义交互都将增加300毫秒延迟

3、tap后延迟350ms再隐藏mask
改动最小,缺点是隐藏mask变慢了,350ms还是能感觉到慢的

4、pointer-events
比较麻烦且有缺陷, 不建议使用mask隐藏后,给按钮下面元素添上 pointer-events: none; 样式,让click穿过去,350ms后去掉这个样式,恢复响应缺陷是mask消失后的的350ms内,用户可以看到按钮下面的元素点着没反应,如果用户手速很快的话一定会发现

27.Jq绑定事件的几种方式?on bind ?

jQuery中提供了四种事件监听方式,分别是bind、live、delegate、on,对应的解除监听的函数分别是unbind、die、undelegate、off

Bind( )是使用频率较高的一种,作用就是在选择到的元素上绑定特定事件类型的监听函数;

Live( )可以对后生成的元素也可以绑定相应的事件,处理机制就是把事件绑定在DOM树的根节点上,而不是直接绑定在某个元素上;

Delegate( )采用了事件委托的概念,不是直接为子元素绑定事件,而是为其父元素(或祖先元素也可)绑定事件,当在p内任意元素上点击时,事件会一层层从event target向上冒泡,直至到达你为其绑定事件的元素;

on( )方法可以绑定动态添加到页面元素的事件,on()方法绑定事件可以提升效率;

28.Jq中如何将一个jq对象转化为dom对象?

方法一:
jQuery对象是一个数据对象,可以通过[index]的方法,来得到相应的DOM对象。
如:var $v =$("#v") ; //jQuery对象
var v=$v[0]; //DOM对象
alert(v.checked) //检测这个checkbox是否被选中

方法二:
jQuery本身提供,通过.get(index)方法,得到相应的DOM对象
如:var $v=$("#v"); //jQuery对象
var v=$v.get(0); //DOM对象
alert(v.checked) //检测这个checkbox是否被选中

29.Jq中有几种选择器?分别是什么?

层叠选择器、基本过滤选择器、内容过滤选择器、可视化过滤选择器、属性过滤选择器、子元素过滤选择器、表单元素选择器、表单元素过滤选择器

30.Jq中怎么样编写插件?

//第一种是类级别的插件开发://1.1 添加一个新的全局函数 添加一个全局函数,我们只需如下定义: 
jQuery.foo = function() {
     alert('This is a test. This is only a test.');  };   //1.2 增加多个全局函数 添加多个全局函数,可采用如下定义: 
jQuery.foo = function() {
       alert('This is a test. This is only a test.');  };  jQuery.bar = function(param) {
      alert('This function takes a parameter, which is "' + param + '".');  };   调用时和一个函数的一样的:jQuery.foo();jQuery.bar();或者$.foo();$.bar('bar');//1.3 使用jQuery.extend(object);  
jQuery.extend({
      foo: function() {
          alert('This is a test. This is only a test.');
        },
      bar: function(param) {
          alert('This function takes a parameter, which is "' + param +'".');
        }
     }); //1.4 使用命名空间// 虽然在jQuery命名空间中,我们禁止使用了大量的javaScript函数名和变量名。// 但是仍然不可避免某些函数或变量名将于其他jQuery插件冲突,因此我们习惯将一些方法// 封装到另一个自定义的命名空间。jQuery.myPlugin = {         foo:function() {         
  alert('This is a test. This is only a test.');         
 },         
 bar:function(param) {         
  alert('This function takes a parameter, which is "' + param + '".');   
 }        }; //采用命名空间的函数仍然是全局函数,调用时采用的方法: 
$.myPlugin.foo();        $.myPlugin.bar('baz');//通过这个技巧(使用独立的插件名),我们可以避免命名空间内函数的冲突。//第二种是对象级别的插件开发//形式1: 
(function($){    
  $.fn.extend({    
   pluginName:function(opt,callback){    
             // Our plugin implementation code goes here.      
   }    
  })    })(jQuery);  //形式2:(function($) {      
   $.fn.pluginName = function() {    
        // Our plugin implementation code goes here.    
   };     })(jQuery);//形参是$,函数定义完成之后,把jQuery这个实参传递进去.立即调用执行。//这样的好处是,我们在写jQuery插件时,也可以使用$这个别名,而不会与prototype引起冲突

31.$('p+.ab')和$('.ab+p') 哪个效率高?

$('p+.ab')效率高

32.$.map和$.each有什么区别

map()方法主要用来遍历操作数组和对象,会返回一个新的数组。$.map()方法适用于将数组或对象每个项目新阵列映射到一个新数组的函数;
each()主要用于遍历jquery对象,返回的是原来的数组,并不会新创建一个数组。

33.编写一个 getElementsByClassName 封装函数?

   <input>   <script> window.onload = function(){ //方法一         
    var Opt = document.getElementById(&#39;sub&#39;);
    var getClass = function(className,tagName){
        if(document.getElementsByTagName){
            var Inp = document.getElementsByTagName(tagName);
            for(var i=0; i<Inp.length; i++){
                if((new RegExp(&#39;(\\s|^)&#39; +className +&#39;(\\s|$)&#39;)).test(Inp[i].className)){
                      return Inp[i];
                    }
                }
            }else if(document.getElementsByClassName){
                return document.getElementsByClassName(className);
        }
    }                 //方法二    var aa = getClass("confirm", "input");
        function getClass(className, targetName){
            var ele = [];
            var all = document.getElementsByTagName(targetName || "*");
            for(var i=0; i<all.length; i++){
                if(all[i].className.match(new RegExp(&#39;(\\s|^)&#39;+confirm+&#39;(\\s|$)&#39;))){    
                    ele[ele.length] = all[i];
                }
            }
            return ele;
        }//方法三    function getObjsByClass(tagName, className){
           if(document.getElementsByClassName){
               alert("document.getElementsByClassName");
               return document.getElementsByClassName(className);
           }else{
               var el = [];
               var _el = document.getElementsByTagName(tagName);
               for(var i=0; i<_el.length; i++){
                   if(_el[i].className.indexOf(className) > -1){
                       alert(_el[i]);
                       el[_el.length] = _el[i];
                   }
               }
               alert(el);
               return el;
           }
       }
   }
 </script>

34.简述下工作流程

My work process in the previous company was roughly like this: after the company's finalization meeting, a simple technical discussion would be held, and then our front-end would make advance technical preparations. The front-end cutter will cut the psd design draft and integrate the css files. We mainly write the JS part, which includes building the front-end framework (large project), writing js business and data persistence operations, we will also write js plug-ins and encapsulate them for easy use, and write JS front-end components and JS test units. Finally Integrate the completed JS part with the HTML page provided by the cutter. Finally, perform functional testing, page compatibility, and product restoration on the completed page. The product is then sealed and submitted for testing. If a BUG occurs, it will be returned to our developers for modification, and then submitted for testing. Finally, if the test is successful, the version will be archived. Wait until all programs are online to conduct online testing.

35. What version control tools are generally used? How does svn lock files?

Purpose of svn locking: To prevent multiple people from changing the same file at the same time To cover each other, the version control system must have a conflict handling mechanism.

Two strategies for svn locking: Optimistic locking: All checked-out files are readable and writable. Modifications to files do not need to obtain file locks. When you check in after modifying the file, it will first You are required to update local files. The version control system will not overwrite your local modifications, but will let you merge conflicts and check in.

Strict locking: All checked-out files are read-only. Any modification to the file must obtain a lock on the file. If others do not have a lock on the file, the version control system will authorize it. Gives you a lock on the file and makes the file editable.

Two locking steps for svn: Optimistic locking: Select the file you want to lock, then right-click the menu and click TortoiseSVN to select Get Lock.

Strict locking: Right-click on the file or directory that you want to strictly lock, use the TortoiseSVN property menu, click New Property, and select the required locking.

36. What is the difference between git and svn?

SVN is a centralized version control system. The version library is centralized on the central server. When working, They all use their own computers, so they first need to get the latest version from the central server, and then do the work. After finishing the work, they need to push the work they have done to the central server. The centralized version control system must be connected to the Internet to work. If it is on a local area network, it is okay, the bandwidth is large enough, and the speed is fast enough. If it is on the Internet, if the network speed is slow, it will be confusing.

Git is a distributed version control system, so it does not have a central server. Everyone’s computer is a complete version library. In this way, you don’t need to be connected to the Internet when working, because the versions are all on your own. on the computer. Since everyone's computer has a complete version library, how can multiple people collaborate? For example, if you have modified file A on your computer, and someone else has also modified file A on your computer, you only need to push your modifications to each other, and you can see each other's modifications.

37. What is the difference between jquery and zepto?

1. For mobile programs, Zepto has some basic touch events that can be used for touch screen interaction (tap events , swipe incident), Zepto does not support IE browser. This is not because Zepto developer Thomas Fucks was confused on the cross-browser issue, but a decision made after careful consideration in order to reduce the file size. Like the jQuery team no longer supports older versions of IE (6 7 8) in version 2.0. Because Zepto uses jQuery syntax, it recommends jQuery as a fallback library on IE in its documentation. That way the program can still run in IE, and other browsers can enjoy the file size advantage of Zepto. However, the APIs of the two are not fully compatible, so be careful and do sufficient research when using this method. test.

2. The difference between Dom operations: jQuery will not take effect when adding id, but Zepto will take effect.

3.zepto is mainly used on mobile devices and only supports newer browsers. The advantage is that the code size is relatively small and the performance is better.
jquery mainly has good compatibility and can run on various PCs and mobile phones. The advantage is that it is compatible with various browsers. The disadvantage is that the amount of code is large, and the performance is not good enough considering compatibility.

38. $(function(){}) and window.onload and $(document).ready(function(){})

window.onload: Used to run the function within the function when all elements of the page, including external reference files, images, etc., are loaded. The load method can only be executed once. If multiple ones are written in the js file, only the last one can be executed.

$(document).ready(function(){}) and $(function(){}) are both used to execute internal functions after the standard DOM elements of the page are parsed into a DOM tree. This function can be written multiple times in the js file. It has a great advantage for js written by multiple people, because all behavioral functions will be executed. Moreover, the $(document).ready() function can be executed after the HMTL structure is loaded. It does not need to wait for time-consuming work such as large file loading or non-existent connections to be completed before execution, which is highly efficient.

39. What is the difference between attr and prop in Jq

For the inherent attributes of the HTML element itself, use the prop method when processing.
For our own custom DOM attributes of HTML elements, use the attr method when processing.

40. Briefly describe the difference between this and when defining properties and methods? Prototype?

This represents the current object. If this is used in the global scope, it refers to the current page object window; if this is used in a function, what this refers to is based on the runtime of this function. What object is called on. We can also use the two global methods apply and call to change the specific pointer of this in the function.

Prototype is essentially a JavaScript object. And every function has a default prototype attribute.

The attribute methods defined on the prototype are shared by all instances. All instances refer to the same object. Modifying the attributes on the prototype by a single instance will also affect all other instances.

41. What is precompiled speech | precompiled processor?

Sass is a CSS preprocessor language that generates CSS code programmatically. Because it is programmable, it has high control flexibility and freedom, making it easy to implement some codes that are difficult to write CSS code directly.

At the same time, because Sass is a language that generates CSS, the written Sass file cannot be used directly. It must be compiled into a CSS file by a compiler before it can be used.

CSS preprocessor is a language used to add some programming features to CSS without considering browser compatibility issues. For example, you can use variables, simple program logic, functions, etc. in CSS Some basic skills in programming languages ​​can make your CSS more concise, more adaptable, and the code more intuitive, among many other benefits. The most commonly used CSS preprocessors are sass, less css, and stylus.

42.ajax and jsonp?

The difference between ajax and jsonp:
Similar points: both request a url
Differences: The core of ajax is to obtain content through xmlHttpRequest
The core of jsonp is dynamic addition <script> tag to call the js script provided by the server. </script>

43.ajax execution process?

1. Create an XMLHttpRequest object, that is, create an asynchronous call object
2. Create a new HTTP request and specify the method, URL and verification information of the HTTP request
3 . Set the function that responds to HTTP request status changes
4. Send HTTP request
5. Get the data returned by the asynchronous call
6. Use JavaScript and DOM to implement partial refresh

44 .xhr object status? readystate?

status is an attribute of the XMLHttpRequest object, indicating the HTTP status code of the response.
readyState is an attribute of the XMLHttpRequest object, used to identify the state of the current XMLHttpRequest object.

45.readystate 0~4

0: Uninitialized state: At this time, an XMLHttpRequest object has been created
1: Ready to send state: At this time , the open method of the XMLHttpRequest object has been called, and the XMLHttpRequest object is ready to send a request to the server.
2: Sent status: At this time, a request has been sent to the server through the send method, but not yet Received a response
3: Receiving status: At this time, the HTTP response header information has been received, but the message body has not been completely received
4: Completed response status: At this time, the HTTP response has been completed Reception of response

46. How many http protocol status codes are there?

200, 201, 302, 304, 400, 404, 500

200: The request was successful
201: The request was successful and the server created a new resource
302: The server is currently responding to requests from a web page in a different location, but the requester should continue to use the original location to respond to future requests.
304: The requested web page has not been modified since the last request. When the server returns this response, no web page content is returned.
400: The server does not understand the syntax of the request.
404: The requested resource (web page, etc.) does not exist
500: Internal server error

47. What is the previous project? What are your main responsibilities? Shopping cart process? Payment function?

Let’s talk about the functional modules that are mainly responsible for:

1) Product module:
1. Product list: product sorting, product filtering, product filtering, product query, product recommendation
2. Product details : Type Recommended Product Introduction Product Details Product Evaluation After-Sales Maintenance

2) Shopping Cart Module: Product number, quantity, price, total amount, freight, shipping options, total freight, delete option from shopping cart, update quantity, checkout , continue shopping, product description, inventory information

48. What is the relationship between sessionStorage and localstroage and cookies, how many bytes can a cookie store at most

What the three have in common : They are all saved on the browser side and have the same origin.

Difference:
1. Cookies are passed back and forth between the browser and the server. SessionStorage and localStorage will not automatically send data to the server, but will only save it locally

2. The storage size limit is also different. Cookie data cannot exceed 4k, but sessionStorage and localStorage are much larger than cookies and can reach 5M.

3. The data validity period is different. sessionStorage: is only valid until the current browser window is closed, and naturally cannot be persisted; localStorage: is always valid, and is saved even when the window or browser is closed, so it is used as a persistent Data; the cookie is only valid until the set cookie expiration time, even if the window or browser is closed

4. Different scopes, sessionStorage is not shared in different browser windows, even on the same page (i.e. data Not shared); localStorage is shared in all homologous windows; cookies are also shared in all homologous windows (i.e. data sharing).

49. What is the difference between get and post in ajax?

Get and post are both methods of data submission.
The data of get is passed through the string spliced ​​after the question mark of the URL. Post transmits data through an HTTP package body.
The transmission volume of get is limited, but there is no limit on post.
The security of get may not be as high as post, so we generally use get to obtain data, and post is generally used to modify data.

50.What is the Gc mechanism? Why are closures not recycling variables and functions?

1. Gc garbage collection mechanism;
2. The external variables are not released, so the small functions within the pointed large functions cannot be released either

51. Brief Describe what you understand about object-oriented?

Everything is an object. Abstracting an object into a class is specifically to abstract the static and dynamic characteristics of an object into attributes and methods, which is to encapsulate the algorithms and data structures of a class of things. In a class, a program is composed of multiple objects and communication between each other.

Object-oriented has encapsulation, inheritance, and polymorphism.
Encapsulation: It hides the details inside the object that do not need to be exposed, so that changes in internal details are separated from the outside world and only rely on interfaces for communication. Encapsulation reduces the complexity of programming. Through inheritance, it becomes easy to create a new class. The tedious work of a class obtaining its non-private methods and public properties from a derived class is left to the compiler. The polymorphism generated by inheritance and implementation of interfaces and the runtime type binding mechanism makes the polymorphism generated by different classes Objects can respond differently to the same message, greatly improving the versatility of the code.

In short, object-oriented features improve the reusability and maintainability of large programs.

52.What is this and what does it represent in different scenarios

(1) function a(){ this ?} //This: points to windows

(2) function b(){ return function(){ this ?}}b()(); //This: points to windows

(3) function c(){ return {s:function(){this} }}c().s(); //This: Points to object

Due to its runtime binding characteristics, the meaning of this in JavaScript is much richer. It can be the global object, the current object or Any object, it all depends on how the function is called.

53. How do you handle data verification? jquery.validate?

In layman's terms, it is a check value calculated on the original data using a specified algorithm to ensure the integrity of the data. The receiver uses the same algorithm to calculate a check value. If it is the same as the check value provided with the data, it means the data is complete.
Use regular expressions to process;
jquery.validate: form validation plug-in

54. How to encrypt the login account password?

Md5

55. In jq, what is the relationship between mouseover mouseenter mouseout mouseleave and hover?

mouseenter与mouseover:
不论鼠标指针穿过被选中元素或其子元素,都会触发mouseover事件。
只有在鼠标指针穿过被选元素时,才会触发mouseentr事件。

mouseout与mouseleave:
不论鼠标离开被选元素还是任何子元素,都会触发mouseout事件。
只有在鼠标指针离开被选元素时,才会触发mouseleave事件。

hover:
hover是一个符合方法,相当于mouseenter+mouseleave。

56.jsonp原理? 缺点?

工作原理:使用script标签实现跨域访问,可在url中指定回调函数,获取JSON数据并在指定的回调函数中执行jquery实现jsop。

缺点:只支持GET方式的jsonp实现,是一种脚本注入行为存在一定的安全隐患。如果返回的数据格式有问题或者返回失败了,并不会报错。

57.除了jsonp 还有什么跨域方式

javascript跨域有两种情况:
1、基于同一父域的子域之间,如:a.c.comb.c.com
2、基于不同的父域之间,如:a.comb.com
3、端口的不同,如:a.com:8080a.com:8088
4、协议不同,如:a.coma.com

对于情况3和4,需要通过后台proxy来解决,具体方式如下:
a、在发起方的域下创建proxy程序
b、发起方的js调用本域下的proxy程序
c、proxy将请求发送给接收方并获取相应数据
d、proxy将获得的数据返回给发起方的js

代码和ajax调用一致,其实这种方式就是通过ajax进行调用的
而情况1和2除了通过后台proxy这种方式外,还可以有多种办法来解决:
1、document.domain+iframe(只能解决情况1):
a、在发起方页面和接收方页面设置document.domain,并将值设为父域的主域名(window.location.hostname)
b、在发起方页面创建一个隐藏的iframe,iframe的源是接收方页面
c、根据浏览器的不同,通过iframe.contentDocument || iframe.contentWindow.document来获得接收方页面的内容
d、通过获得的接收方页面的内容来与接收方进行交互
这种方法有个缺点,就是当一个域被攻击时,另一个域会有安全漏洞出现。

58.如何使用storage 对js文件进行缓存

由于sessionStorage - 针对一个 session 的数据存储,所以我们一般利用localStorage储存js文件,只有在第一次访问该页面的时候加载js文件,以后在访问的时候加载本地localStorage执行

59.如何确保ajax或连接不走缓存路径

在Ajax中使用Get请求数据不会有页面缓存的问题,而使用POST请求可是有时候页面会缓存我们提交的信息,导致我们发送的异步请求不能正确的返回我们想要的数据

$.post(url,data ,ranNum:Math.random()} ,function(data){})

ranNum : 这个是防止缓存的核心,每次发起请求都会用Math.random()方法生成一个随机的数字,这样子就会刷新url缓存

60.split() join()?

前者是切割成数组的形式,
后者是将数组转换成字符串

61.slice()  splice()?

slice() 方法可从已有的数组中返回选定的元素。
splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。

62.typeof?typeof [ ]返回数据类型是?

//判断基本数据类型;var a=[];typeof a输出object;//本来判断一个对象类型用typeof是最好的,不过对于Array类型是不适用的,//可以使用 instanceof操作符:       var arrayStr=new Array("1","2","3","4","5");    
       alert(arrayStr instanceof Array); //当然以上在一个简单的页面布局里面是没有问题的,如果是复杂页面情况,//入获取的是frame内部的Array对象,可以用这个函数判断:       function isArray(obj) {      
          return Object.prototype.toString.call(obj) === '[object Array]';       
       }

63.disabled readyonly?

readonly只针对input(text / password)和textarea有效,而disabled对于所有的表单元素都有效,当表单元素在使用了disabled后,当我们将表单以POST或GET的方式提交的话,这个元素的值不会被传递出去,而readonly会将该值传递出去。

64.同步异步?

1、进程同步:就是在发出一个功能调用时,在没有得到结果之前,该调用就不返回。也就是必须一件一件事做,等前一件做完了才能做下一件事

2、异步的概念和同步相对。当一个异步过程调用发出后,调用者不能立刻得到结果。实际处理这个调用的部件在完成后,通过状态、通知和回调来通知调用者。

65.promise

Promise的构造函数接收一个参数,是函数,并且传入两个参数:resolve,reject,分别表示异步操作执行成功后的回调函数和异步操作执行失败后的回调函数。

66.函数fn1 函数fn2 函数fn3,如果想在三个函数都执行完成后执行某一个事件应该如何实现?

//1、设置事件监听。//2、回调函数:function fn1(){
       console.log("执行fn1");
       fn2();}function fn2(){
       console.log("执行fn2");
       fn3();}function fn3(){
       console.log("执行fn3");
       mou();}function mou(){
       console.log("执行某个函数");}fn1();

67.JavaScript提供了哪几种“异步模式”?

1、回调函数(callbacks)
2、事件监听
3、Promise对象

68.什么是移动端的300ms延迟?什么是点击穿透?解决方案?

移动端300ms延迟:假定这么一个场景。用户在 浏览器里边点击了一个链接。由于用户可以进行双击缩放或者双击滚动的操作,当用户一次点击屏幕之后,浏览器并不能立刻判断用户是确实要打开这个链接,还是想要进行双击操作。因此,浏览器 就等待 300 毫秒,以判断用户是否再次点击了屏幕。也就是说,当我们点击页面的时候移动端浏览器并不是立即作出反应,而是会等上一小会儿才会出现点击的效果。

点击穿透:假如页面上有两个元素A和B。B元素在A元素之上。我们在B元素的touchstart事件上注册了一个回调函数,该回调函数的作用是隐藏B元素。我们发现,当我们点击B元素,B元素被隐藏了,随后,A元素触发了click事件。这是因为在移动端浏览器,事件执行的顺序是touchstart > touchend > click。而click事件有300ms的延迟,当touchstart事件把B元素隐藏之后,隔了300ms,浏览器触发了click事件,但是此时B元素不见了,所以该事件被派发到了A元素身上。如果A元素是一个链接,那此时页面就会意外地跳转。

300ms延迟解决方案:
(1) 禁用缩放,在html文档头部加meta标签如下:


(2) 更改默认的视口宽度 (响应式布局,消除了站点上可能存在的双击绽放的请求)


(3) Css touch-action
touch-action:none;在该元素上的操作不会触发用户代理的任何行为,无需进行3000ms延迟判断。

(4) FastClick为解决移动端浏览器300毫秒延迟开发的一个轻量级的库
点击穿透解决方案:
(1)只用touch
(2)只用click
(3)tap后延迟350ms再隐藏mask
(4)pointer-events

69.变量作用域?

//变量作用域:一个变量的作用域是程序源代码中定义这个变量的区域。全局变量拥有全局作用域,//在js代码中任何地方都是有定义的。在函数内声明的变量只在函数体内有定义,它们是局部变量,//作用域是局部性的。函数参数也是局部变量,它们只在函数体内有定义。var a = "";window.b=''”;function(e) {
       var c= "";
       d="";
       e="";}function go() {
       console.info(this);//window       return function() {
               console.info(this); // window               return {
                b:function(){
                       console.info(this); //b的父对象                   }
            }
       }}go()().b();

70.call & apply 两者之间的区别  

call和apply都是改变this指向的方法,区别在于call可以写多个参数,而apply只能写两个参数,第二个参数是一个数组,用于存放要传的参数。

71.call和apply 有什么好处?

用call和apply:实现更好的继承和扩展,更安全。

72.谁是c的构造函数?

function ab() {
         this.say = ""; } ab.constructor = {} ab.name = ''; var c = new ab(); //构造函数默认指向函数本身,ab是一个类,它的构造函数是它本身,//然后ab.constructor={};ab的构造函数就指向{}了,c是ab的实例化对象,c的构造函数就是{}//通过使用new的时候,创建对象发生了那些改变? 当使用new操作时,会马上开辟一个块内存,//创建一个空对象,并将this指向这个对象。接着,执行构造函数ab(),对这个空对象进行构造//(构造函数里有什么属性和方法都一一给这个空白对象装配上去,这就是为何它叫构造函数了)。

73.sass和less有什么区别?

1. The compilation environment is different. The installation of Sass requires a Ruby environment, which is processed on the server side, while Less needs to introduce less.js to process the Less code and output css to the browser. You can also use Less in the development process, and then Compile it into a css file and put it directly into the project.

2. The variable symbols are different, less is @, and scss is $, and their scopes are also different, less is a block-level scope

3. Output settings, Less There is no output setting. Sass provides 4 output options, nested, compact, compressed and expanded. Nested: Nested indented CSS code (default). Expanded: Expanded multi-line CSS code. Compact: Simple format CSS code. Compressed: Compressed. css code

4. Sass supports conditional statements, you can use if{}else{}, for{} loops, etc., but less cannot

5. Reference external css files, sass references external The file must start with _. If the file name is in the shape of an underscore _, Sass will think that the file is a reference file and will not compile it into a css file. There is no difference between referencing external files in less and @import in css.

6. The tool libraries of sass and less are different. Sass has a tool library called Compass. Simply put, the relationship between sass and Compass is a bit like the relationship between Javascript and jQuery. Compass is a tool library for sass. On its basis, a series of useful modules and templates are encapsulated to supplement and strengthen the functions of Sass. Less has the UI component library Bootstrap. Bootstrap is a well-known front-end UI component library in web front-end development. Part of the source code of Bootstrap's style files is written using less syntax.

Summary: Whether it is sass or less, it can be regarded as a high-level language based on CSS. Its purpose is to make CSS development more flexible and powerful. The function of sass is more powerful than that of less, and it can basically It is said to be a real programming language, but less is relatively clear and easy to use, and has relatively loose requirements on the compilation environment. Considering that compiling sass requires installing Ruby, and the Ruby official website is not accessible in China, I personally prefer less in actual development.

74.Bootstrap benefits?

Adaptive and responsive layout, 12-grid system, unified interface style and css style are conducive to team development. The discipline for writing flexible, stable, high-quality HTML and CSS code.

75. How to manage projects during development? gulp?

When I develop, I use front-end workflow management tools such as gulp to manage projects. Gulp is a new generation of front-end project building tool. You can use gulp and its plug-ins to compile your project code (less, sass), compress your js and css code, and even compress your images, and merge files. Compress files, syntax check, monitor file changes, test, convert binary, convert pictures and other functions. Gulp only has a small API, so it is very easy to learn. Achieve good project management.

76. What is the purpose of compression and merging? How to optimize http requests?

1) One of the most important best practices for web performance optimization is to reduce HTTP requests. The main way to reduce HTTP requests is to merge and compress JavaScript and CSS files.

CSS Sprites (CSS sprites): Put the entire site's icons in an image file, and then use the CSS background-image and background-position attributes to position a small part of them.

Merging scripts and style sheets; Image map: Use the image map tag to define a client image map (image map refers to an image with a clickable area) See for details: club.topsage.com/thread

When placing static resources such as image js/css on a static server or CDN server, try to use different domain names. This can prevent cookies from contaminating each other and reduce round-trip data for each request.

Css replaces images and caches some data

Use less location.reload(): Using location.reload() will refresh the page. When refreshing the page, all resources of the page (css, js, img, etc.) ) will request the server again. It is recommended to use location.href="current page url" instead of location.reload(). When using location.href, the browser will read local cache resources.

77. How many ajax request methods are there (8 types)?

1)$.get(url,[data],[callback])
2)$.getJSON(url,[data],[callback])
3)$ .post(url,[data],[callback],[type])
4)$.ajax(opiton)
5)$.getScript( url, [callback] )
6) jquery object .load( url, [data], [callback] )
7) serialize() and serializeArray()

78. How to copy a dom element?

Native Js method: var p = document.getElementsByTagName('p')[0];
var clone = p.cloneNode();
Jquery method: $('p').clone() ;
By default, the .clone() method does not copy events bound in the matching element or its descendant elements. However, you can pass a Boolean parameter to this method and set this parameter to true to copy the event together, that is, .clone(true).

79. Array sorting method (sort)? Sort? Chinese character sorting?

Array sorting methods: reverse() and sort(). The reverse() method reverses the order of array items.
Eg:var values ​​= [0, 1, 5, 10, 15]; values.sort();//0,1,10,15,5
var values ​​= [1, 2, 3, 4, 5]; values.reverse();//5,4,3,2,1

Sort in js (for details, refer to: tuicool.com/articles/Ij
Use sort sorting, bubble sorting, quick sorting, insertion sorting, Hill sorting, selection sorting
Merge sort

localeCompare() method is used for string encoding sorting
localeCompare method: Returns a value indicating whether the two strings are the same in the current locale.

80. Briefly describe what you understand about object-oriented?

Object-oriented is based on the philosophical view that everything is an object. Abstracting an object into a class is specifically to abstract the static characteristics and dynamic characteristics of an object into attributes and methods, that is, to abstract a class into The algorithms and data structures of things are encapsulated in a class, and the program is composed of multiple objects and communication between them.

Object-oriented has encapsulation, inheritance, and polymorphism.

Encapsulation: It hides the details inside the object that do not need to be exposed, so that changes in internal details are separated from the outside world and only rely on interfaces for communication. Encapsulation reduces the complexity of programming. Through inheritance, a new class variable can be created The tedious work of a class obtaining its non-private methods and public properties from a derived class is left to the compiler. The polymorphism generated by inheriting and implementing interfaces and the runtime type binding mechanism makes different classes The generated objects can respond differently to the same message, greatly improving the versatility of the code.

In short, the object-oriented features improve the reusability and maintainability of large programs.

81.How to create an object?

1. Factory pattern
2. Constructor pattern
3. Prototype pattern
4. Mixed constructor and prototype pattern
5. Dynamic prototype pattern
6. Parasitic Constructor Pattern
7. Safe Constructor Pattern

Program design pattern? Factory pattern? Publish and subscribe?
1) Design pattern is not a certain piece of code in a certain language, design A pattern is an idea that provides possible solutions to various problems encountered when coding. It is more inclined to a kind of logical thinking rather than a universal code block.
Design patterns are mainly divided into three types: creative, structural and behavioral.
Creative patterns: singleton pattern, abstract factory pattern, builder pattern, factory pattern and prototype pattern.
Structural modes: adapter mode, bridge mode, decorator mode, combination mode, appearance mode, flyweight mode and proxy mode.
Behavioral patterns: template method pattern, command pattern, iterator pattern, observer pattern, mediator pattern, memo pattern, interpreter pattern, state pattern, strategy pattern, chain of responsibility pattern and visitor pattern.

2) Similar to the creational pattern, the factory pattern creates objects (considered as products in the factory) without specifying the specific class of the created object.
The factory pattern defines an interface for creating objects. This interface determines which class to instantiate by the subclass. This pattern defers instantiation of a class to subclasses. Subclasses can override interface methods to specify their own object types when creating.

3) The observer pattern is also called the publish-subscribe pattern. It defines a one-to-many relationship, allowing multiple observer objects to monitor a certain topic object at the same time. When the status of the topic object changes, All observing objects will be notified. It is composed of two types of objects, topics and observers. The topic is responsible for publishing events, and the observer observes the subject by subscribing to these events. The publisher and the subscriber are completely decoupled and do not know the existence of the other. Just share the name of a custom event.
(The design pattern is really too advanced. My friends can learn it by themselves based on online examples. I am really helpless)

82.commonjs?requirejs?AMD|CMD|UMD?

1. CommonJS is to formulate specifications for the performance of JS. NodeJS is the implementation of this specification. Webpack is also written in the form of CommonJS. Because js does not have the function of modules, CommonJS came into being. But it doesn't work in the browser. The modules defined by CommonJS are divided into: {module reference (require)} {module definition (exports)} {module identification (module)}

2.RequireJS is a JavaScript module loader.​ ​ RequireJS has two main methods: define() and require(). These two methods basically have the same declaration and they both know how to load dependencies and then execute a callback function. Unlike require(), define() is used to store code as a named module. Therefore, the callback function of define() needs to have a return value as this module definition. These similarly defined modules are called AMD (Asynchronous Module Definition).

3.AMD is the standardized output of RequireJS module definition during the promotion process. AMD asynchronously loads modules. Its module supports various types of modules such as objects, functions, constructors, strings, JSON, etc. The AMD specification applies to the define method to define the module.

4.CMD is the standardized output of module definitions in the promotion process of SeaJS
The difference between AMD and CDM:
(1) For dependent modules, AMD is executed in advance (as if now Delayed execution is also possible), CMD is delayed execution.
(2) AMD advocates dependencies up front, and CMD advocates dependencies nearby.
(3) AMD advocates multiplexing interfaces, while CMD advocates single-use interfaces.
(4) Differences in writing standards.

5.umd is a blend of AMD and CommonJS.
AMD browser first principle development asynchronous loading module.
CommonJS module is developed based on the server-first principle and chooses to load synchronously. Its modules do not need to be packaged (unwrapped modules). This forces people to come up with another more general model UMD (Universal Module Definition), hoping to solve cross-platform solutions. UMD first determines whether the module (exports) that supports Node.js exists. If it exists, use the Node.js module mode.

83. What are the inheritance methods of js?

1. Use object impersonation to implement inheritance
2. Use the call and Apply methods to change the function context to implement inheritance
3. Prototype chain inheritance

84 . JavaScript prototype, prototype chain? What are its characteristics?

In JavaScript, there are two types of values, primitive values ​​and object values. Each object has an internal property [[prototype]], which we usually call prototype. Prototype The value can be an object or null. If its value is an object, the object must also have its own prototype. This forms a linear chain, which we call a prototype chain. ​

To access the prototype of an object, you can use the Object.getPrototypeOf method in ES5, or the __proto__ attribute in ES6. The function of the prototype chain is to implement inheritance. For example, if we create a new array, the array method is based on the prototype of the array. Inherited.

85. What does eval do?

Its function is to parse the corresponding string into JS code and run it; you should avoid using eval, which is unsafe and very performance-consuming (twice, once to parse into a js statement, and once to execute).

86. What is the difference between null and undefined?

undefined means the value of the variable is declared but not initialized, and null means it is ready to save the object, but the value of the object has not been actually saved. From a logical perspective, null represents a null object pointer.

87. Do you know JSON?

JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript. The data format is simple, easy to read and write, and takes up little bandwidth.

88. What are the ways to delay loading js?

defer and async, dynamic creation of DOM (most commonly used), asynchronous loading of js on demand

89. What is ajax? Asynchronous javascript and XML refer to a web development technology for creating interactive web applications. By exchanging a small amount of data with the server in the background, AJAX can enable asynchronous updates of web pages. This means that parts of a web page can be updated without reloading the entire page.

90. What is the difference between synchronization and asynchronousness?

Javascript synchronization means sync, which means: the code is executed in sequence. JavaScript asynchronous means async, which means: the code is executed out of sequence.' Skip 'execution and wait until some other code has been executed before executing it, which becomes asynchronous.

91. How to solve the cross-domain problem?

Jsonp, iframe, window.name, window.postMessage, set proxy page on the server

92. What are the methods of asynchronous loading?

(1) defer, only supports IE
(2) async: true
(3) Create a script, insert it into the DOM, and callBack after loading

93. jQuery What is the difference from jQuery UI?

jQuery is a js library that mainly provides selectors, property modification, event binding, etc.
jQuery UI is a plug-in designed based on jQuery and utilizing jQuery’s extensibility. Provides some commonly used interface elements, such as dialog boxes, dragging behaviors, resizing behaviors, etc.

94. What performance optimization methods do you have?

(1) Reduce the number of http requests: CSS Sprites, JS, CSS source code compression, and image size control are appropriate; web page Gzip, CDN hosting, data cache, and image server.

(2) Front-end template JS data reduces bandwidth waste caused by HTML tags. The front-end uses variables to save AJAX request results. Each time local variables are operated, there is no need to request, reducing the number of requests

( 3) Use innerHTML instead of DOM operations to reduce the number of DOM operations and optimize javascript performance.

(4) When there are many styles to be set, set className instead of directly operating style.

(5) Use less global variables and cache the results of DOM node search. Reduce IO read operations.

(6) Avoid using CSS Expression (css expression), also known as Dynamic properties (dynamic properties).

(7) Image preloading, put the style sheet at the top, put the script at the bottom and add a timestamp.

(8) Avoid using table in the main layout of the page. The table will not be displayed until the content is completely downloaded. The display is slower than the p css layout.

95. What happens in the process from entering the URL to the completion of page loading and display on a page? (The more detailed the process, the better)

Find the browser cache
DNS resolution, find the IP address corresponding to the domain name, redirect (301), and issue a second GET request
Carry out HTTP protocol session
Client sends header (request header)
Server returns header (response header)
html document starts downloading
Document tree is established, and the file of the specified MIME type is required according to the mark request
File display

The work done by the browser is roughly divided into the following steps:
Loading: perform domain name resolution according to the requested URL, initiate a request to the server, and receive files (HTML, JS, CSS, images, etc.).
Parsing: perform syntax analysis on loaded resources (HTML, JS, CSS, etc.), and suggest corresponding internal data structures (such as HTML DOM tree, JS (object) attribute table, CSS style rules, etc.)

96. Disadvantages of ajax

1. Ajax does not support the browser back button.
2. Security issues AJAX exposes the details of interaction with the server.
3. The support for search engines is relatively weak.
4. Destroyed the exception mechanism of the program.
5. Not easy to debug

Recommended tutorial: "JS Tutorial"

The above is the detailed content of 96 basic front-end JS interview questions (including answers). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:知乎. If there is any infringement, please contact admin@php.cn delete
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.