Some time ago to ali interview an experience, share it with you!

The brain is mixed remember not much, remember how much record how much…

Use CSS to achieve a continuous animation effect

animation:mymove 5s infinite;
@keyframes mymove {
from {top:0px; }to {top:200px;}
}
Copy the code

The usage of animation

value describe
animation-name Specifies the name of the KeyFrame to bind to the selector.
animation-duration Specifies the time, in seconds or milliseconds, to complete the animation.
animation-timing-function Specifies the speed curve of the animation.
animation-delay Specifies the delay before the animation begins.
animation-iteration-count Specifies how many times an animation should play.
animation-direction Specifies whether the animation should take turns playing backwards.

Use JS to achieve a continuous animation effect

The initial idea was to use a timer, but the final thought was not complete, and the interviewer gave the answer to use requestAnimationFrame.

  • Timer idea
var e = document.getElementById('e')
var flag = true;
var left = 0;
setInterval((a)= > {
    left == 0 ? flag = true : left == 100 ? flag = false : ' '
    flag ? e.style.left = ` ${left++}px` : e.style.left = ` ${left--}px`
}, 1000 / 60)
Copy the code
  • requestAnimationFrameBecause I haven’t used this beforeAPISo I learned it now.
// Compatibility processing
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function(callback){
            window.setTimeout(callback, 1000 / 60); }; }) ();var e = document.getElementById("e");
var flag = true;
var left = 0;

function render() {
    left == 0 ? flag = true : left == 100 ? flag = false : ' ';
    flag ? e.style.left = ` ${left++}px` :
        e.style.left = ` ${left--}px`;
}

(function animloop() { render(); requestAnimFrame(animloop); }) ();Copy the code

Shortcomings please point out (after all, it is now learning) incidentally check the advantages:

  • Browsers can optimize parallel animation sequences, rearrange sequences more sensively, and combine actions within a single rendering cycle for smoother animation
  • Resolve millisecond inaccuracies
  • Avoid overrendering (rendering too often,tabNot visible pause, etc.) Note:requestAnimFrameThe timer was also the first of its kindcancelAnimationFrame.

Fixed width on the right, adaptive on the left

The first:

<style>
body{
    display: flex;
}
.left{
    background-color: rebeccapurple;
    height: 200px;
    flex: 1;
}
.right{
    background-color: red;
    height: 200px;
    width: 100px;
}
</style>
<body>
    <div class="left"></div>
    <div class="right"></div>
</body>
Copy the code

The second,

<style>
    div {
        height: 200px;
    }
    .left {
        float: right;
        width: 200px;
        background-color: rebeccapurple;
    }
    .right {
        margin-right: 200px;
        background-color: red;
    }
</style>
<body>
    <div class="left"></div>
    <div class="right"></div>
</body>
Copy the code

I can think of two.

Horizontal and vertical center

The first kind of

#container{
    position:relative;
}

#center{
    width:100px;
    height:100px;
    position:absolute;
    top:50%;
    left:50%;
    transform: translate(50%, 50%); }Copy the code

The second,

#container{
    position:relative;
}

#center{
    width:100px;
    height:100px;
    position:absolute;
    top:50%;
    left:50%;
    margin: -50px 0 0 -50px;
}
Copy the code

The third kind of

#container{
    position:relative;
}

#center{
    position:absolute;
    margin:auto;
    top:0;
    bottom:0;
    left:0;
    right:0;
}
Copy the code

A fourth flex

#container{
    display:flex;
    justify-content:center;
    align-items: center;
}
Copy the code

The difference between four kinds of positioning

  • staticIs the default
  • relativeRelative position Offset relative to its original position and still in the standard document flow
  • absoluteAbsolute location relative to the most recently located ancestor element, has location (refers topositionnotstaticAncestor element, using the most recent ancestor element as a reference standard. If there are no located ancestor elements, tobodyThe element is an offset reference base, completely removed from the standard document flow.
  • fixedA fixed positioning element is positioned relative to the window, meaning that it stays in the same position even as the page scrolls. A fixed location element does not retain the space it should have on the page.

Do you use Flex layouts a lot?

Since the project is considered compatible with IE9, it is not much to use directly

How does mobile adaptation work?

Reactive layouts using media queries that load CSS for different screen widths.

What is the difference between let and var?

Let adds a new variable declaration command for ES6. It is similar to var, but with the following differences:

  • varThe scope of the declared variable is within the function of the statement, and the variable is promoted
  • letThe declared variable is scoped within the code block in which the statement resides. There is no variable promotion
  • letDuplicate declarations are not allowed.

Why can var repeat declarations? (I don’t know.)

When we execute code, we can simply allocate a chunk of memory for the new variable, name it a, and assign it a value of 2, but at runtime the compiler and engine do two additional things: check whether the variable has already been declared:

  • First the compiler dissects the code, encountering it from left to rightvar a, the compiler will ask if the scope already has a callaIf it does not exist, the scope declares a new variableaIf it already exists, ignore itvarI’m going to go ahead and compilea = 2Compiled into executable code for use by the engine.
  • The engine to meeta=2“Will also ask if there are variables in the current scopea, if exists, willaThe assignment for2Because the compiler ignored the duplicate declaration in step 1var, and already exists in scopea, so the repeated declaration will be overridden without an error. If not, look up the scope chain, if the variable is eventually foundaThen it is assigned2If not found, the call scope declares a variableaAnd assignment2.Refer to the link

Encapsulate a function that takes the timer time. Then executes the callback function.

function sleep (time) {
  return new Promise((resolve) = > setTimeout(resolve, time));
}
Copy the code

A question about what this refers to

Something like that, I don’t know

obj = {
    name: 'a'.getName : function () {
        console.log(this.name); }}var fn = obj.getName
obj.getName()
var fn2 = obj.getName()
fn()
fn2()
Copy the code

CommonJS require/exports and ES6 import/export.

  • CommonJSAn important feature of a module is that it executes at load time, that is, when the script code is loadedrequire“, it will all be executed. Once a module is “looping”, only the parts that have been executed are printed, not the parts that have not been executed.
  • ES6Modules are referenced dynamically if usedimportLoading variables from a module, those variables are not cached, but become a reference to the loaded module, requiring the developer to ensure that the value is actually fetched.
  • import/exportIt’s always going to compile torequire/exportsTo execute.
  • CommonJSThe specification states that within each module,moduleThe variable represents the current module. This variable is an object, itsexportsAttribute (i.e.,module.exports) is the external interface. Loading a module is actually loading the modulemodule.exportsProperties.
  • exportCommands specify external interfaces and must establish a one-to-one correspondence with variables inside the module.

One line of code for array de-duplication?

[...new Set([1.2.3.1.'a'.1.'a']]Copy the code

Using addEventListener, click on Li to pop up the content, and add li dynamically

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
Copy the code

This question is not answered 😨😨

var ulNode = document.getElementById("ul");
    ulNode.addEventListener('click'.function (e) {
        if (e.target && e.target.nodeName.toUpperCase() == "LI") { alert(e.target.innerHTML); }},false);
Copy the code

How do you tell if two objects are equal?

obj={
    a:1.b:2
}
obj2={
    a:1.b:2
}
obj3={
    a:1.b:'2'
}
Copy the code

The initial idea is to iterate, but in the end, it seems not clear, check, it seems to be converted to a string to determine.

JSON.stringify(obj)==JSON.stringify(obj2);//true
JSON.stringify(obj)==JSON.stringify(obj3);//false
Copy the code

What performance optimizations did the project make?

  • To reduceHTTPNumber of requests
  • To reduceDNSThe query
  • useCDN
  • Avoid redirection
  • Lazy loading of images
  • To reduceDOMNumber of elements
  • To reduceDOMoperation
  • The use of externalJavaScriptCSS
  • The compressionJavaScriptCSS, fonts, pictures, etc
  • To optimize theCSS Sprite
  • useiconfont
  • Font cutting
  • Multi-domain distribution divides content into different domain names
  • As far as possible to reduceiframeuse
  • Avoid imagesrcIs empty
  • Put the stylesheet in
  • Put the script at the bottom of the page welcome add…

How does modular development work?

Use namespaces.

Ever used Webpack?

I said it was used in the Vue project and then stopped asking.

Did Gulp write his own missions? Or the same module for both?

Do not know how how answer, not all use module to write yao, then say to use module.

How to redirect Vue router to router link?

router.go(1)
router.push('/')
Copy the code

What is the difference between Vue router jump and location.href?

Router is a hash to change location.href is a page jump to refresh the page

How does Vue bidirectional binding work?

Object. DefineProperty

Can you implement bidirectional binding? 😰 😰

<body>
    <div id="app">
        <input type="text" id="txt">
        <p id="show-txt"></p>
    </div>
    <script>
        var obj = {}
        Object.defineProperty(obj, 'txt', {
            get: function () {
                return obj
            },
            set: function (newValue) {
                document.getElementById('txt').value = newValue
                document.getElementById('show-txt').innerHTML = newValue
            }
        })
        document.addEventListener('keyup'.function (e) {
            obj.txt = e.target.value
        })
    </script>
</body>
Copy the code

What’s the difference between React and Vue?

Set and Map data structures (😨😨)

  • ES6New data structures are providedSetIt is similar to an array, but the values of the members are unique and there are no duplicate values.
  • ES6providesMapData structure. It is a collection of key-value pairs similar to objects, but the range of “keys” is not limited to strings. Values of all types (including objects) can be used as keys. In other words,ObjectThe structure provides a “string-value” correspondence,MapThe structure provides value-value correspondence, which is a more complete oneHashStructure implementation.

What is the difference between WeakMap and Map?

  • WeakMapThe structure andMapThe structure is basically similar, except that it only accepts objects as key names (nullValues of other types are not accepted as key names, and the object to which the key names refer is not counted in the garbage collection mechanism.
  • WeakMapThe biggest benefit is that you avoid memory leaks. One onlyWeakMapAs akeyThe referenced objects are collected by the garbage collector.
  • WeakMapOwned andMapA similarset(key, value)Get (key), from the (key),delete(key) andclear()Method, without any iteration-related attributes or methods.

Rearrange and redraw

  • Part of the render tree (or the entire render tree) needs to be re-analyzed and the node sizes recalculated. This is called rearrangement. Note that there is at least one rearrange-initialization page layout.
  • Parts of the screen need to be updated when the node’s geometry changes or when the style changes, such as changing the element’s background color. Such updates are called redraws.

What circumstances trigger rearrangement and redraw?

  • Add, delete, updateDOMnode
  • throughdisplay: noneTo hide aDOMNode – Triggers rearrangement and redraw
  • throughvisibility: hiddenTo hide aDOMNodes – only trigger redraw because there are no geometric changes
  • Move or add to the pageDOMNode adding animation
  • Add a style sheet and adjust the style properties
  • User actions, such as resizing a window, changing font size, or scrolling.

Browser cache

Browser caches are divided into strong cache and negotiated cache. When a client requests a resource, the process for obtaining the cache is as follows:

  • Let’s start with some of this resourcehttp headerDetermine whether it matches the strong cache. If it matches, the cache resources are directly obtained from the local server without sending requests to the server.
  • When the strong cache does not hit, the client sends a request to the server, and the server sends a request through anotherrequest headerVerify that the resource matches the negotiated cache, calledhttpThen verify that, if a match is hit, the server will request back, but does not return the resource, but tells the client to directly get the resource from the cache, the client will get the resource from the cache after receiving the return;
  • Strong and negotiated caches have in common that the server does not return the resource if the cache is hit;
  • The difference is that the strong cache does not send requests to the server, but the negotiated cache does.
  • When the negotiation cache also dies, the server sends the resource back to the client.
  • whenctrl+f5When the page is forced to refresh, it is loaded directly from the server, skipping the strong cache and negotiated cache.
  • whenf5When the page is refreshed, the strong cache is skipped, but the negotiated cache is checked.

Strong cache

  • Expires (This field ishttp1.0The value is an absolute timeGMTTime string in format, representing the expiration time of the cached resource.
  • Cache-control :max-age (This field ishttp1.1The specification for strong caching utilizes itmax-ageValue to determine the maximum lifetime of the cache resource in seconds.

Negotiate the cache

  • Last-modified (value is when the resource was Last updated and is returned with server response)
  • If-modified-since (Compares two times to determine If the resource was Modified between requests. If not, the negotiated cache is hit.)
  • ETag (unique identifier for resource content, returned with server response)
  • If-none-match (The server compares the if-none-match in the request header with the ETag of the current resource to determine whether the resource has been modified between requests. If not, it matches the negotiation cache.)

WeakMap’s clear() method is deprecated, thanks @feibuli for correcting it

Obj3 was written incorrectly, corrected Thanks @silent comrade

Some of the answers may not be accurate, I hope you light spray

Gold digging technical certificate activity link: https://juejin.cn/post/1