当前位置:网站首页>Working principle and practice of browser

Working principle and practice of browser

2022-04-23 06:53:00 zjLOVEcyj

Browser architecture

One 、 Know what's happening when the browser is running JS

contain :BOM、DOM、ECMAScript

    (function(context, undefined){
    
        const _class = ['js', 'browser', 'vue']

        //  Mount to global 
        window.classArr = _class.map(item => item)

        //  Get the current page address 
        const _url = location.href

        //  Set up tab title 
        document.title = 'zhaowa class'

        //  Get render nodes 
        document.getElementById('app')
    })(this)

    //  Questioning : Learn about browsers JS The execution state of 
    //  sketch :
    // ECMAScript -  Basic logic 、 Data processing 
    // DOM -  For browser windows , Corresponding operation of text 
    // BOM -  For the processing of the browser's own regional capabilities 

Two 、BOM

1. location

location.href => ‘https://www.zhaowa.com/search?class=browser#comments’ => Path bar all
.orgin => ‘https://www.zhaowa.com’
.protocol => ‘https:’
.host => ‘www.zhaowa.com’
.port => ‘’
.pathname => ‘/search/’
.search => ‘?class=browser&id=2’
.hash => ‘#comments’

    .assign('') //  Jump to the designated path =>  Replace pathname
    .replace('') //  ditto , Also replace browsing history 
    .reload()  // Equivalent to refreshing the current page 
    .toString() //  Output current address string 
  • Interview direction :
  1. location In itself api operation - Extract relevant information 、api Inter comparison => assign vs replace
  2. Routing related : Jump 、 Parameters 、 operation => scene : You can go back to (history)、 Refresh or not (hash)=> replace Replace assign、 Portability parameter
  3. url Handle - Regular or Handwriting js Handle
  4. URI & URL: uniform resource identifier / locator

history

history.state => Store the status of the current page

history.pushState()
.replaceState()

  • Interview direction - Routing direction : history and hash Advantages and disadvantages of the model

3. navigator

  • A large collection of browser system information
    navigator.userAgent //  Get the system environment information of the current user 
  • Interview direction
  1. userAgent Read information => Browser compatibility 、 Report information
  2. Shear plate 、 keyboard

4. screen

Characterize the display area - Screen

  • Interview direction - Judge the size of the area
    window Window judgment :
    Global entry :
    window.innerHeight
    window.innerWidth
    Get... From the text :
    document.documentElement.clientHeight
    document.documentElement.clientWidth
    document.body.clientWidth
    document.body.clientWidth

    Of web page view size -> offsetHeight = clientHeight + Scroll bar + Frame
    document.documentElement.offsetHeight
    document.documentElement.offsetWidth
    document.body.offsetHeight
    document.body.offsetWidth

    Dynamic positioning :
    scrollLeft / scrollTop - Distance from normal left / Up scrolling distance
    offsetLeft / offsetTop - Distance from normal left / Up the distance

    el.getBoundingClientRect()
    el.getBoundingClientRect().top
    el.getBoundingClientRect().left
    el.getBoundingClientRect().bottom
    el.getBoundingClientRect().right

    • Compatibility - IE Yes, there will be more 2 Pixels

    3、 ... and 、 Event Event model

        <div id="app">
            <p id="dom"></p>
        </div>
    
        //  Bubbling  - ms: p => div => body => HTML => document
        //  Capture  - ns: document => HTML => body => div => p
    
        el.addEventListener(event, function, useCapture) //  The default value is false
    
        //  Questioning :
        // 1.  How to stop the spread of time 
        event.stopPropgation() 
        //  Be careful : Prevent delivery behavior  =>  Default events cannot be blocked 
    
        // 2.  Block default events  - a 
        event.preventDefault()
    
        // 3.  Prevent the triggering of multiple other similar event handlers bound by the current node 
        event.stopImmediatePropagation()
    
        //  The core of extended interview :  Compatibility  &  performance 
        // 4.  Handwriting compatibility event binding 
        // IE - attachEvent vs addEventListener
        //  difference :
        // a.  The ginseng :attachEvent  For the event name, you need to add 'on'
        // b.  Execution order :attachEvent -  After binding, execute ; addEventListener -  Bind first and execute first 
        // c.  Unbundling :detachEvent vs removeEventListener
        // d.  block :event.cancelBubble = true vs event.stopPropgation() 
        // e.  Default event interception :event.returnValue = false vs event.preventDefault()
    
        class bindEvent {
          
            constructor(element) {
          
                this.element = element;
            }
            //  binding 
            addEventListener = (type, handler) => {
          
                if(this.element.addEventListener) {
          
                    this.element.addEventListener(type, handler, false)
                } else if(this.element.attachEvent) {
          
                    this.element.attachEvent('on' + type, () => {
          
                        handler.call(element);
                    })
                } else {
          
                    this.element['on' + type] = handler;
                }
            }
            //  Unbundling 
            removeEventListener = (type, handler) => {
          
                if(this.element.removeEventListener) {
          
                    this.element.removeEventListener(type, handler, false)
                } else if(this.element.detachEvent) {
          
                    this.element.detachEvent('on' + type, () => {
          
                        handler.call(element);
                    })
                } else {
          
                    this.element['on' + type] = null;
                }
            }
            //  block 
            static stopPropgation(e) {
          
                if (e.stopPropagation) {
          
                    e.stopPropagation()
                } else {
          
                    e.cancelBubble = true;
                }
            }
            //  Default intercept 
            static preventDefault(e) {
          
                if(e.preventDefault) {
          
                    e.preventDefault()
                } else {
          
                    e.returnValue = false;
                }
            }
        }
    
    // 5. performance optimization  -  Event agent 
        <ul class="list">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
        </ul> 
        <div class="content"></div>
    
        var list = document.querySelector('.list');
        var li = list.getElementsByTagName('li');
    
        //  Hard touch hard 
        for(var n = 0; n < li.length; n++) {
          
            li[n].addEventListener('click', function() {
          
                //  Business logic 
            })
        }
    
        //  After agency  -  Use events to deliver 
        function onClick(e) {
          
            var e = e || window.event;
    
            if(e.target.nodeName.toLowCase() === 'li') {
          
                //  Business logic 
                var liList = this.querySelectorAll('li');
                // ……
            }
        }
    
        list.addEventListener('click', onClick, false)
    

    Four 、 The network layer

        //  Instantiation 
        const xhr = new XMLHttpRequest();
    
        // Initialize build 
        xhr.open(method, url, async) // get/post;  Requested address ;  Whether it is an asynchronous request 
    
        //  Method  - send
        xhr.send(data) // get -  It can not be transmitted or passed in null,post - encodeURIComponent Code splicing 
    
        //  receive 
        // xhr.readyStatus - 0 -  Not yet established open;1 -  Has called open; 2 -  Has called send; 3 -  The request has been received and returned ; 4-  The request has been completed 
        xhr.onreadystatuschange = () => {
          
            if(xhr.readyStatus === 4) {
          
                //  Judge http Status code 
                if(xhr.status >= 200 &&
                    xhr.status < 300 ||
                    xhr.status == 304) {
          
                        // xhr.responseText
                }
            }
        }
    
        //  Timeout time 
        xhr.timeout = 30000
        xhr.ontimeout = () => {
          
            //  After a timeout 
        }
    
        //  Interview direction 
        // 1、TCP => HTTP/HTTPs
        // 2、 Status code  => 2xx 4xx 5xx | 3xx =>  Browser cache  =>  Strong cache (Expires + cache-control) /  Negotiate the cache (last-modified + Etag)
    
        //  Encapsulate handwriting 
        ajax({
          
            url: 'reqUrl',
            method: 'get',
            async: true,
            timeout: 30000,
            data: {
          
                payload: 'text'
            }
        }).then(
            res => {
          }
            err => {
          }
        ).catch(err => {
          })
    
        //  Realization :
        function ajax(options) {
          
            const {
          
                url,
                method,
                async,
                data,
                timeout
            } = options;
    
            const xhr = new XMLHttpRequest()
    
            //  Configure timeout events 
            if (timeout) {
          
                xhr.timeout = timeout;
            }
    
            return new Promise((resolve, reject) => {
          
                //  success 
                xhr.onreadystatuschange = () => {
          
                    if(xhr.readyStatus === 4) {
          
                        //  Judge http Status code 
                        if(xhr.status >= 200 &&
                            xhr.status < 300 ||
                            xhr.status == 304) {
          
                                //  Return interceptor 
                                resolve(xhr.responseText)
                        } else {
          
                            reject()
                        }
                    }
                }
    
                //  Failure 
                xhr.onerror = err => reject(err)
                xhr.ontimeout = () => reject('timeout')
    
                //  Pass parameter processing 
                let _params = []
                let encodeData = ''
                if (data instanceof Object) {
          
                    for(let key in data) {
          
                        //  Parameter code 
                        _params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
                    }
                    encodeData = _params.join('&')
                }
    
                // method Judge connection 
                if (method === 'get') {
          
                    const index = url.indexOf('?')
    
                    if(index === -1) {
          
                        url += '?'
                    } else if(index !== url.length -1) {
          
                        url += '&'
                    }
    
                    url += encodeData
                }
    
                //  Establishing a connection 
                xhr.open(method, url, async)
                //  Request interceptor ……
                //  Send a request 
                if (method === 'get') {
          
                    xhr.send(null)
                } else {
          
                    // post
                    xhr.setRequestHeader(
                        'content-type': 'application/x-www-form-urlencoded'
                    )
                    xhr.send(encodeData)
                }
            })
        }
        //  Interview point : content-type =>  Content type  =>  browser  => ff chrome
    

5、 ... and 、 Browser principle

Interview questions : from url Enter into the page to show what happened - Get resources => Render the page

    // DOM
    // CSSOM - CSS Parse into a tree data structure 
    // Render Tree: DOM + CSSOM Make trees 
    // Layout module: Calculation Render Tree The specific status and location of each node 
    // Painting: Present to the screen 

    //  technological process 
    // Url => HTML analysis  - JS + DOM + CSSOM => render tree / JS + css perform  => layout => painting

    //  Vertical segmentation 
    // bytes(62 48 65 2C……) => characters(<html></html>) => Tokens(tag tree) => Nodes(html|head|body) => DOM | CSSOM

    //  Interview direction 
    // 1.  Rendering process 
    // 2.  Analytical way  =>  Engine writing (DSL)
    // 3. **  performance optimization 

版权声明
本文为[zjLOVEcyj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230555334385.html