Table of contents
2. Common events of the window object
Fourth, the execution mechanism of JavaScript
Understand the execution order of JavaScript:
5.1, location object properties
5.2 Common methods of location
Eight, element offset offset series
1. BOM
BOM is the browser object model, which provides a series of objects that interact with the browser window independently of the content, and its core object is window. Some objects of browser window interaction learned by BOM
2. Common events of the window object
Common events window loading and window resizing
event |
Registration issue | illustrate |
---|---|---|
window load event |
1.window.onload = function(){} 2.window.addEventListener(‘load’,function(){}) |
onload is a traditional way of registering events that can only be written once. If there are more than one, the last one will prevail. addEventListener has no limit. |
resize window event | 1.window.onresize = function(){} 2.window.addEventListener(‘resize’,function(){}) |
1. This event will be triggered whenever the size of the window changes in pixels. 2. Often use this event to complete the responsive layout. window.innerWidh gets the width of the current screen |
Replenish
- window.onload is a window (page) loading event. When the document content is fully loaded, the event will be triggered (including images, script files, CSS files, etc.), which is to call the processing function.
- Window.addEventListener('DOMContentLoaded', function(){}) Only when the DOM is loaded, excluding images, falsh, css, etc., the DOMContentLoaded event can be triggered, and the loading speed is faster than load
3. Timer
The Window object provides us with 2 timer methods: setTimeout() setInterval()
Function | window can be omitted | Cancels a timer previously established by calling |
---|---|---|
The timer executes the calling function after the timer expires | window.setTimeout(call function, [delay in milliseconds]); | window.clearTimeout(timeoutID) |
Every this time, call the callback function once | window.setInterval(callback function, [interval milliseconds]); | window.clearInterval(timeoutID); |
Replenish:
- The setTimeout() method executes the calling function after the timer expires, so it is also called a callback function, because there may be many timers, so we often assign an identifier to the timer
- The identifier of the timer when passing the parameter when canceling the timer previously established by calling
Fourth, the execution mechanism of JavaScript
JavaScript is single-threaded, which means it can only do one thing at a time. This means that all tasks need to be queued, and the next task will only be executed after the previous task is completed. The problem caused by this is: If the execution time of JS is too long, the rendering of the page will be incoherent, resulting in the feeling of blocking the rendering and loading of the page.
In order to solve this problem and make full use of the computing power of the CPU, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, so synchronous and asynchronous appear in JS
Synchronization: Execute tasks sequentially according to the arrangement of tasks. This task is also called synchronous task
Asynchronous: while task A is being executed, task B can also be executed, and this process is realized through a callback function in Javascript
There are three main types of asynchronous tasks:
- Ordinary events, such as click, resize, etc.;
- Resource loading, such as load, error, etc.;
- Timers, including setInterval, setTimeout, etc.
Understand the execution order of JavaScript:
//synchronous task: Output: 1 2 3
console.log(1);
console.log(2);
console.log(3);
//synchronous plus asynchronous tasks: output 1 4 3 2console.log(1);
setTimeout(function() {
console.log(2);
},1000)
setTimeout(function() {
console.log(3);
},0)
console.log(4);
All tasks will have a judgment before execution. Synchronous tasks enter the main thread for execution in turn, and asynchronous tasks enter the Event Table and register functions. When the things specified in the Event Table are completed, this function will be moved to the Event Queue. When the task in the execution stack is empty, the function is executed from the Event Queue. Repeatedly
In addition to synchronous tasks and asynchronous tasks in a broad sense, JavaScript also has a more refined definition of tasks:
- macro-task (macro task): including the overall code script, setTimeout, setInterval
- micro-task (micro-task): Promise, process.nextTick
Different types of tasks will enter the corresponding Event Queue.
The order of the event loop determines the execution order of the js code. After entering the overall code (macro task), start the first cycle. All microtasks are then executed. Then start from the macro task again, find one of the task queues to be executed, and then execute all the micro tasks.
Execute macro task ===> execute micro task ===> execute another macro task ===> loop continuously
console.log(1);
setTimeout(function() {
console.log(2)
},1000);
new Promise(function(resolve) {
console.log(3);
resolve();
}
).then(function() {
console.log(4)
});console.log(5);
The result of judging in a synchronous and asynchronous manner should be: 1, 3, 5, 2, 4 but in fact the result is: 1, 3, 5, 4, 2
Five, Location object
The Window object provides us with a location property for getting or setting the URL of the form, and it can be used to parse the URL. Because this property returns an object, we also refer to this property as the location object.
URL: Uniform Resource Locator
Syntax : Protocol://host[:port]/path/[?query]#fragment
- protocol: Communication protocols commonly used http, ftp, maito, etc.
- Host: host (domain name)
- Port: The default port of the scheme used when the port number is optional and omitted, such as the default port of http is 80
- Path: The path has zero or more strings separated by / symbols, generally used to represent a directory or file address on a level-by-level basis
- The Query parameter is in the form of a key-value pair separated by & symbols
- Fragment: Fragment#The following content is long seen in the link anchor
5.1, location object properties
object properties | return value |
---|---|
location.href | returns or sets the entire URL |
location.search | return parameter |
location.hash | Return Fragment#Following content is common in link anchors |
location.port | return port number |
location.host | return domain name |
location.pathname | return path |
5.2 Common methods of location
method | illustrate |
---|---|
location.assign() | Like href, you can jump to the page (also known as a redirection page) and generate a history record to go back to the page |
location.replace() | Replace the current page, because the history is not recorded, so you cannot go back to the page |
location.reload() | Reload the page, equivalent to the refresh button f5, if the parameter is true, force refresh ctrl+f5 |
Six, navigator object
1. The navigator object contains information about the browser, and it has many attributes.
2. We commonly use userAgent, which can return the value of the user-agent header sent by the client to the server.
3. The following front-end code can determine whether the user is using Which terminal opens the page, if it is opened by a PC, we will jump to the page on the PC side, if it is opened by a mobile phone, we will jump to the page on the mobile side
if((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
window.location.href = ""; //手机
} else {
window.location.href = ""; //电脑
}
Seven, history object
The Window object provides us with a history object to interact with the browser history, which contains URLs that the user (in the browser window) has visited
method | illustrate |
---|---|
history.back() | back function |
history.forward() | forward function |
history.go() | Back function parameters in previous years If it is 1, go forward one page; if it is -1, go back one page |
Eight, element offset offset series
Offset is translated as an offset. We can dynamically get the position (offset), size, etc. of the element by using the related attributes of the offset series. Note: the returned value does not have a unit
offset | style |
---|---|
offset can get the style value in any style sheet | style can only get the style value in the inline style sheet |
The value obtained by the offset series has no unit | style.width gets a string with units |
offsetWidth contains padding+border+width | style.width gets a value that does not include padding and border |
Attributes such as offsetWidth are read-only attributes, which can only be obtained but not assigned | style.width is a readable and writable attribute, which can be obtained or assigned |
Therefore, we want to get the size and position of the element, it is more appropriate to use offset | So if we want to change the value of the element, we need to change it with style |
offset series attribute |
effect |
---|---|
element.offsetParent |
Returns the element that is the positioned parent of this element, or body if none of the parents are positioned |
element.offsetTop |
Returns the offset of the element relative to the position above the parent element |
element.offsetLeft |
Returns the offset of the element relative to the left border of the positioned parent element |
element.offsetWidth | Returns the width of itself including padding, border, and content area, and the returned value does not have the unit px |
element.offsetHeight | Returns the height of itself including padding, border, and content area, and the returned value does not have the unit px |
Element viewport client series
The translation of client is the client. We use the relevant attributes of the client series to obtain the relevant information of the element's visible area. Through the relevant attributes of the client series, we can dynamically obtain the border size and element size of the element.
client series attributes |
effect |
element.clientTop |
Returns the size of the border on the element |
element.clientLeft |
Returns the size of the element's left border |
element.clientWidth | Returns the width of itself including padding and content area, excluding borders, and returns without units |
element.clientHeight | Returns the height of itself including padding and content area, excluding borders, and returns without units |
element scroll scroll series
The translation of scroll is scrolling. We can dynamically get the size of the element, scrolling distance, etc. by using the related attributes of the scroll series.
scroll series properties |
effect |
element.scrollTop |
Returns the upper side distance being rolled up, the return value does not have a unit |
element.scrollLeft |
Returns the left distance that will be rolled up, and the returned value has no unit |
element.scrollWidth | Returns the actual width of its own content, without borders, and returns without units |
element.scrollHeight | Returns the actual height of its own content, without borders, and returns without units |
onscroll滚动条滚动事件当我们滚动条发生变化会触发事件
注意:元素被卷去的头部是 元素.scrollTop,如果是页面被卷去的头部则是 window.pageYOffset