当前位置:网站首页>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 :
- location In itself api operation - Extract relevant information 、api Inter comparison => assign vs replace
- Routing related : Jump 、 Parameters 、 operation => scene : You can go back to (history)、 Refresh or not (hash)=> replace Replace assign、 Portability parameter
- url Handle - Regular or Handwriting js Handle
- 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
- userAgent Read information => Browser compatibility 、 Report information
- 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.clientWidthOf web page view size -> offsetHeight = clientHeight + Scroll bar + Frame
document.documentElement.offsetHeight
document.documentElement.offsetWidth
document.body.offsetHeight
document.body.offsetWidthDynamic positioning :
scrollLeft / scrollTop - Distance from normal left / Up scrolling distance
offsetLeft / offsetTop - Distance from normal left / Up the distanceel.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
边栏推荐
猜你喜欢
随机推荐
Scientists say Australian plan to cull up to 10,000 wild horses doesn’t go far enough
postMan 传参总结
压力测试工具 Jmeter
js中entries(),keys(),values() , some(), Object.assign()遍历数组用法
多线程
The getfield () method in TP5 changes, and TP5 gets the value of a single field
sql中的 IF 条件语句的用法
js中的作用域与作用域链
freeCodeCamp----shape_calculator练习
Your brain expands and shrinks over time — these charts show how
Usage of if conditional statements in SQL
SignalR实现从服务端主动发送数据到客户端
Centos8 builds php8 0.3 operating environment
Color string conversion
.Net Core 下使用 Quartz —— 【6】作业和触发器之触发器的日历
端口占用1
Leak detection and vacancy filling (IX) -- Procedure
Multi cycle verification of El form
freeCodeCamp----budget & category 练习
tp5 报错variable type error: array解决方法









