Function anti-shake, function throttling, browser local storage, caching mechanism (interview focus!!!)

Function anti-shake, function throttling, browser local storage, caching mechanism (interview focus!!!)

Function debounce (debounce)

Concept: Delay the action to be executed. If it is triggered again during the delay period, cancel the previously started action and restart the timing.

Example: The computer goes to sleep after a black screen without operation for one minute, and the mouse moves once in the 40s to restart counting.

Implementation: Timer

Application: When searching, wait for the user to input all the content before starting the query

<script>
        let inputNode = document.getElementById("user_input")
        let id
        inputNode.addEventListener('keyup',function(){
    
    
            if(id){
    
    
                clearTimeout(id);
            }
            let value = inputNode.value
            id = setTimeout(() => {
    
    
                sendAjax(value)
            }, 200);  //时间为0.2s~0.3s之间
        })
        
        function sendAjax(data){
    
    
            // console.log('发送了一次ajax请求,内容为'+ data)
            console.log(`发送了一次Ajax请求,内容为${
      
      data}`)
        }
    </script>

Function throttling (throttle)

Concept: Set a specific time, so that the function is executed only once in a specific time, not frequently executed

Example: In a gun game, the bullets will not connect into a line if the mouse is held down without letting go. (Quickly exceed your own frequency)

Implementation: timer, identification

Requirement: When the mouse wheel is scrolling, print once every two seconds

<script>
        let canlog = true
        document.body.onscroll = function(){
    
    
            if(canlog){
    
    
                    console.log(1)
                    canlog = false
                    setTimeout(() => {
    
    
                        canlog = true
                    }, 2000)
                }
        }
    </script>

Browser local storage

Cookie SessionStorage LocalStorage These three can be used to store data on the browser side, and they are all key-value pairs of string type.

  • session

  • sessionStorage: The container used by the browser to store data. (front end)

  • Session session storage, a way to store data on the server side. (rear end)

Web Storage

For the collective term of SessionStorage and LocalStorage, the content size is generally 5-10MB

The browser implements the local storage mechanism through the Window.SessionStorage and Window.LocalStorage properties.

Related API:
1. xxxxxStorage.setItem('key','value');
This method accepts a key name and value as parameters, and will add the key value pair to the storage. If the key name exists, update its corresponding value .

  1. var data = xxxxxStorage.getItem('person');
    This method accepts a key name as a parameter and returns the value corresponding to the key name.

  2. xxxxxStorage.removeItem('key');
    This method accepts a key name as a parameter, and deletes the key name from the storage.

  3. xxxxxStorage.clear()
    calling this method will clear all the keys in the storage

Note: The content stored in SessionStorage will disappear when the browser window is closed.
The content stored in LocalStorage needs to be manually cleared before it disappears.

<body>
    <button id="btn1">保存数据</button>
    <button id="btn2">读取数据</button>
    <button id="btn3">删除数据</button>
    <button id="btn4">清空数据</button>
<script>
    let btn1 = document.getElementById('btn1')
    let btn2 = document.getElementById('btn2')
    let btn3 = document.getElementById('btn3')
    let btn4 = document.getElementById('btn4')

    let person = {name:'kebo',age:18}
    //保存
    btn1.onclick = ()=>{
        sessionStorage.setItem('demo',JSON.stringify(person))
    }
    //读取
    btn2.onclick = ()=>{
        console.log(JSON.parse(sessionStorage.getItem('demo')))
    }
    //删除
    btn3.onclick = ()=>{
        sessionStorage.removeItem('demo')
    }
    //清空
    btn4.onclick = ()=>{
        sessionStorage.clear()
    }
</script>
</body>

Data synchronization/browser cross-tab communication (interview focus)

storage event:

  1. Triggered when the Storage object changes (that is, when a data item is created/updated/deleted, Storage.clear() will only be triggered once)

  2. Changes that occur within the same page will not work

  3. Only changes that occur on other pages under the same domain name will take effect. (The modified page will not trigger the event, the page shared with it will trigger the event)
    key: the modified or deleted key value, if clear() is called, it is null
    newValue: the newly set value, if clear() is called, it is null
    oldValue: call the value before the change, if clear() is called, it will be null
    url: the url of the document that triggered the script change
    storageArea: the current storage object How to
    use:
    window.addEventListener('storage',function (event) { / /Write specific business logic here })

    数据同步1
    <input type="text" id="input">
        <script>
            let input = document.getElementById('input')
            input.onblur = function(){
          
          
                localStorage.setItem('data',input.value)
            }
        </script>
    
    数据同步2
    <input type="text" id="input2">
       <script>
            //得知道它啥时候存进去了
            let input2 = document.getElementById('input2')
            window.addEventListener('storage',function(event){
          
          
                input2.value = event.newValue
               // input2.value = localStorage.getItem('data') 也可以写,但是将data写死了
            })
        </script>
    

###Browser storage support
http://dev-test.nemikor.com/web-storage/support-test/

Browser's caching mechanism

Understanding the cache

  1. Cache definition: The browser stores the data previously requested by the user on the local disk. When the visitor needs to change the data again, there is no need to send the request again, and the data is directly obtained from the local browser.

  2. The benefits of caching:

    1. Reduce the number of requests
    2. Save bandwidth and avoid wasting unnecessary network resources
    3. Reduce the pressure on the server
    4. Improve the loading speed of browser web pages and improve user experience

Cache classification

1. Strong cache

​ (1) No request is sent to the server, and the data is directly obtained from the local storage

​ (2) The status code of the requested resource is 200 ok (from memo/disk cache) cache (computer high-speed buffer)

2. Negotiation cache

​ (1) Send a request to the server, and the server will judge whether it hits the negotiation cache according to the resource in the request header

​ (2) If it hits, it returns a 304 status code to notify the browser to read the resource from the cache, that is, the negotiation is successful

​ (3) Negotiation failed: the server returns the required homepage and other things

3. The common points of strong caching and negotiation caching:

​ Read resources from the browser

4. Differences:

​ Strong cache does not send requests to the server

​ Negotiate the cache to send a request to the server, and decide whether to use the cache according to the information returned by the server

Strong cache

Request: request header + data carried in the request requestHeader

Response: response header + responseHeader data to you

Header parameters in strong cache

Request: request header + data carried in the request requestHeader

Response: response header + responseHeader data to you

  1. expires: (Response Header, expiration time of strong cache)

    1. This is the specification at the time of http1.0; its value is an absolute time GMT format time string, for example Mon, 10 Jun 2015 21:31:12 GMT, if the time of sending the request is before expires, then the local cache is always valid, otherwise it will send the request to the server to get it Resources

      eg: For example, if it expires on November 15, 2020, the webpage is strongly cached on 2020.11.1, and the cache will not be strong on November 16, 2020.

  2. cache-control: max-age=number (production date of strong cache)

    1. This is the header information that appears in http1.1. It is mainly judged by the max-age value of this field. It is a relative value; the first request time of the resource and the validity period set by Cache-Control are calculated. Resource expiration time, and then compare this expiration time with the current request time. If the request time is before the expiration time, it can hit the cache, otherwise it will not work;

      Second (s) as a unit, when expires and cache-control conflict, use cache-control

    2. Commonly used values ​​of cache-control:

      1. no-cache: 不使用本地缓存,需要使用协商缓存。先与服务器确认返回的响应是否被更改,如果之前的响应中存在Etag,那么请求的额时候会与服务器端进行验证,如果资源为被更改则使用缓存。
      2. no-store: 直接禁止游览器缓存数据,每次用户请求该资源,都会向服务器发送一个请求,每次都会下载完整的资源。
      3. public:可以被所有的用户缓存,包括终端用户和CDN等中间代理服务器。
      4. private:只能被终端用户的浏览器缓存,不允许CDN等中继缓存服务器对其缓存。
      5. <font color=red>注意:当cache-control与Expires共存的时候cache-control的优先级高</font>
      

Negotiate cached header parameters


Important: The server determines whether the cache resource is available for negotiation, so the client and the server must communicate through a certain identifier, so that the server can determine whether the requested resource can be cached and accessed.

  • Last-Modified/If-Modified-Since: Both values ​​are time strings in GMT format

  • The negotiation cache returns the last modification time, and the next request must carry this time in the past

    1. The browser requests a resource from the server for the first time. When the server returns the resource, it adds a Last-Modified header to the header of the responder. This header represents the last modification time of the resource on the server.
    2. When the browser requests this resource from the server again, add the header of If-Modified-Since to the header of the request. The value of this header is the value of Last-Modified returned in the previous request.
    3. When the server receives the resource request again, it judges whether the resource has changed according to the If-Modified-Since passed by the browser and the last modification time of the resource on the server. If there is no change, it will return 304 Not Modified, but the resource content will not be returned; if If there is a change, the resource content will be returned normally. When the server returns a 304 Not Modified response, the Last-Modified header will not be added to the response header, because since the resource has not changed, the Last-Modified will not change. This is the response header when the server returns 304
    4. After the browser receives the 304 response, it will load the resource from the cache
    5. If the negotiation cache is not hit, when the browser loads the resource directly from the server, the Last-Modified Header will be updated when it is reloaded. When the next request is made, If-Modified-Since will enable the Last-Modified value returned last time
    6. legend:

  • Etag/If-None-Match
    1. These two values are generated by the server unique identification string for each resource , as long as there are resources to change this value will change
    2. The judgment process is similar to Last-Modified/If-Modified-Since

  • Existing Last-Modified He Sheng Etag
    1. The emergence of Etag in HTTP1.1 is mainly to solve several problems that are more difficult to solve in Last-Modified
    2. Some files may be changed periodically, but their content does not change (only the modification time). At this time, we do not want the client to think that the file has been modified and re-GET
    3. Some files are modified very frequently, such as modification in less than a second (for example, N times in 1s), the granularity that If-Modified-Since can check is s-level, and this modification cannot be judged (or It is said that UNIX records MTIME can only be accurate to the second);
    4. Some servers cannot accurately get the last modification time of the file.

  • summary:
    • Using Etag can more accurately control the cache, because Etag is a unique identifier on the server side of the corresponding resource automatically generated by the server or generated by the developer.

    • Last-Modified and ETag can be used together. The server will verify the ETag first. If they are consistent, it will continue to compare Last-Modified, and finally decide whether to return 304.

​ [External link image transfer failed. The origin site may have an anti-leech chain mechanism. It is recommended to save the image and upload it directly (img-5wmoNlx9-1605323253709) (F:\WEB\WEB\009-git,svn, modularization, optimization\ 009-git,svn,modularization, optimization\performance optimization_stu\courseware&summary\07_caching diagram.png)]

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-miEJWrAh-1605323253712) (F:\WEB\WEB\009-git,svn, modularization, optimization\009 -git,svn,modularization, optimization\performance optimization_stu\illustration\02_browser rendering process.png)]

CSS Interview Test Site

1. Clear the float

2. Hidden elements (methods)

3. Holy Grail, double

4.css precompiler less stylas

Guess you like

Origin blog.csdn.net/rraxx/article/details/109688123