1. BOM overview
BOM = Browser Object Model
It provides an object that interacts with the browser window independently of the content, and its core object is window
BOM consists of a series of related objects, and each object provides many methods and attributes
BOM lacks standards. The standardization organization of JavaScript syntax is ECMA, and the standardization organization of DOM is W3C. BOM was originally a part of Netscape browser standards
DOM | BOM |
Document object model | Browser object model |
DOM treats a document as an object | Treat the browser as an object |
The top-level object of DOM is document | The top-level object of BOM is window |
DOM mainly learns how to manipulate page elements | BOM learns some objects that interact with the browser window |
DOM is the W3C Standard Specification | BOM is defined by browser manufacturers on their respective browsers, with poor compatibility |
1.1 composition of BOM
BOM is larger than DOM. It contains DOM.
window object is the top-level object of browser, which has dual roles
It is an interface for JS to access the browser window
It is a global object. Variables and functions defined in the global scope will become the properties and methods of window objects
You can omit window when calling. The dialog boxes learned earlier belong to window object methods, such as alert(), prompt(), etc.
Note: a special attribute under window is window name
//Variables defined in the global scope will become the properties of the window object
var num = 10; console.log(window.num); // 10 // Functions defined in the global scope become methods of window objects function fn() { console.log(11); } console.fn(); // 11 var name = 10; //Do not use this name variable. There is a special attribute window under window name console.log(window.num);
2. Common events for window objects
2.1. Window loading event
window.onload is a window (page) loading event. When the document content is fully loaded, this event will be triggered (including images, script files, CSS files, etc.), and the processing function will be called.
window.onload = function(){ }; // perhaps window.addEventListener("load",function(){});
be careful:
With window Onload can write the JS code above the page elements
Because onload is to execute the processing function after all the page contents are loaded
window.onload can only be written once in the traditional event registration mode
If there are more than one, the last window will be used Onload shall prevail
If you use addEventListener, there are no restrictions
document.addEventListener('DOMContentLoaded',function(){})
Receive two parameters:
When the DOMCountentLoaded event is triggered, only when the DOM is loaded, excluding style sheets, pictures, flash, etc
If there are many pictures on the page, it may take a long time from user access to onload trigger
The interaction effect cannot be realized, which will inevitably affect the user experience. At this time, DOMContentLoaded event is more appropriate.
2.1.1 differences
load and other page contents are all loaded, including page dom elements, pictures, flash, css, etc
DOMContentLoaded means that after the DOM is loaded, it can be executed without pictures, flash css, etc. the loading speed is faster than load
<script> // window.onload = function() { // var btn = document.querySelector('button'); // btn.addEventListener('click', function() { // alert('click me '); // }) // } // window.onload = function() { // alert(22); // } window.addEventListener('load', function() { var btn = document.querySelector('button'); btn.addEventListener('click', function() { alert('Click me'); }) }) window.addEventListener('load', function() { alert(22); }) document.addEventListener('DOMContentLoaded', function() { alert(33); }) // load and other page contents are all loaded, including page dom elements, pictures, flash css and so on // DOMContentLoaded means that the DOM can be loaded without pictures, false CSS, etc. the loading speed is faster than load </script>
2.2. Window resizing event
window.onresize is the processing function called when the window resizing loading event is triggered
window.onresize = function() {}
//Or
window.addEventListener('resize',function(){});
This event is triggered whenever the window size changes in pixels
We often use this event to complete responsive layout. window.innerWidth the width of the current screen
<body> <script> window.addEventListener('load', function() { var div = document.querySelector('div'); window.addEventListener('resize', function() { console.log(window.innerWidth); console.log('Changed'); if (window.innerWidth <= 800) { div.style.display = 'none'; } else { div.style.display = 'block'; } }) }) </script> <div></div> </body>
3. Timer
The window object provides us with two timers
setTimeout()
setInterval()
3.1. SetTimeout
The setTimeout() method is used to set a timer that executes the calling function after the timer expires.
window.setTimeout(Call function,[Milliseconds of delay]);
be careful:
window can be omitted
This calling function
You can write functions directly
Or write the function name
Or take the string 'function name ()' (not recommended)
The number of milliseconds of delay is omitted. The default is 0. If it is written, it must be milliseconds
Because there may be many timers, we often assign an identifier to the timer
The calling function setTimeout() is also called callback function
Ordinary functions are called directly according to the code sequence, and this function needs to wait for events, and the function will not be called until the event arrives, so it is called callback function.
<body> <script> // 1. setTimeout // Syntax specification: window SetTimeout (calling function, delay time); // 1. This window can be omitted when calling // 2. The delay time unit is milliseconds, but it can be omitted. If omitted, the default is 0 // 3. This calling function can directly write the function and the function name. There is another way to write 'function name()' // 4. There may be many timers in the page. We often add identifiers (names) to timers // setTimeout(function() { // console.log('time is up '); // }, 2000); function callback() { console.log('It exploded'); } var timer1 = setTimeout(callback, 3000); var timer2 = setTimeout(callback, 5000); // setTimeout('callback()', 3000); // We don't advocate this way of writing </script> </body>
3.2. clearTimeout() stop timer
The timer was established by calling the timeout() method previously
window.clearTimeout(timeoutID)
be careful:
window can be omitted
The parameter inside is the identifier of the timer
<body> <button>Click stop timer</button> <script> var btn = document.querySelector('button'); var timer = setTimeout(function() { console.log('It exploded'); }, 5000); btn.addEventListener('click', function() { clearTimeout(timer); }) </script> </body>
3.3. setInterval() timer
setInterval() method calls a function repeatedly, and calls the callback function every other time
window.setInterval(Callback function,[Number of milliseconds between]);
window can be omitted
This callback function:
You can write functions directly
Or write the function name
Or take the character 'function name ()'
The first execution is also executed after milliseconds, and then every milliseconds
<body> <script> // 1. setInterval // Syntax specification: window Setinterval (calling function, delay time); setInterval(function() { console.log('Continue output'); }, 1000); // 2. When the setTimeout delay time is up, call the callback function and call it only once to end the timer // 3. setInterval calls the callback function every time after this delay time. It will be called many times and the function will be called repeatedly </script> </body>
3.4. clearInterval() stop timer
The clearInterval () method cancels the timer previously established by calling setInterval()
be careful:
window can be omitted
The parameter inside is the identifier of the timer
<body> <button class="begin">Start timer</button> <button class="stop">Stop Timer </button> <script> var begin = document.querySelector('.begin'); var stop = document.querySelector('.stop'); var timer = null; // The global variable null is an empty object begin.addEventListener('click', function() { timer = setInterval(function() { console.log('ni hao ma'); }, 1000); }) stop.addEventListener('click', function() { clearInterval(timer); }) </script> </body>
3.5 this direction
The point of this cannot be determined when the function is defined. Only when the function is executed can we determine who this is pointing to
At this stage, let's first understand some of this points
In the global scope or ordinary function, this points to the global object window (note that this in the timer points to the window)
Who calls this in the method call
this in the constructor points to the constructor instance
<body> <button>click</button> <script> // This points to the problem. Generally, the final point of this is the object that calls it
// 1. In the global scope or ordinary function, this points to the global object window (note that this in the timer points to the window)
console.log(this); function fn() { console.log(this); } window.fn(); window.setTimeout(function() { console.log(this); }, 1000);
// 2. Who calls this in the method call
var o = { sayHi: function() { console.log(this); // This refers to o this object } } o.sayHi(); var btn = document.querySelector('button'); // btn.onclick = function() { // console.log(this); // this refers to the btn button object // } btn.addEventListener('click', function() { console.log(this); // this refers to the btn button object }) // 3. this in the constructor refers to the instance of the constructor function Fun() { console.log(this); // this refers to the fun instance object } var fun = new Fun(); </script> </body>
4. JS execution mechanism
4.1. JS is a single thread
A major feature of JavaScript language is single thread, that is, you can only do one thing at a time. This is due to the mission of the birth of JavaScript, a scripting language - Javascript was born to deal with user interaction in pages and operate dom. For example, we can't add and delete a DOM element at the same time. You should add it first and then delete it.
Single thread means that all tasks need to be queued, and the next task will be executed only after the previous task is completed. The problem caused by this is: if JS is executed for a long time, it will cause the rendering of the page to be inconsistent, resulting in the feeling of page rendering loading blocking.
4.2. A problem
What is the result of the execution of the following code?
console.log(1); setTimeout(function() { console.log(3); },1000); console.log(2);
So what is the result of the following code execution?
console.log(1); setTimeout(function() { console.log(3); },0); console.log(2);
4.3. Synchronous and asynchronous
In order to solve this problem, using the computing power of multi-core CPU, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads
Thus, synchronization and asynchrony appear in JS.
Synchronization:
Execute the next task after the previous task is completed
Asynchronous:
While doing this, you can also deal with other things
Synchronization task
Synchronization tasks are executed on the main thread to form an execution stack
Asynchronous task
Asynchrony in JS is realized through callback function
There are three types of asynchronous tasks
Common events, such as click,resize, etc
Resource loading, such as load,error, etc
Timer, including setInterval,setTimeout, etc
Add asynchronous task related callback function to task queue
Execute the synchronization task in the stack first
The asynchronous task (callback function) is put into the task queue
Once all synchronous tasks in the execution stack are executed, the system will read the asynchronous tasks in the task queue in order, so the read asynchronous tasks end the waiting state, enter the execution stack and start execution
Now let's look at the question we just asked:
console.log(1); setTimeout(function() { console.log(3); },1000); console.log(2);
The results and order of execution are 1, 2 and 3
console.log(1); setTimeout(function() { console.log(3); },0); console.log(2);
The results and order of execution are 1, 2 and 3
// 3. Third question
console.log(1); document.onclick = function() { console.log('click'); } console.log(2); setTimeout(function() { console.log(3) }, 3000)
Synchronous tasks are executed in the execution stack. Asynchronous tasks are processed by asynchronous processes and placed in the task queue. After the tasks in the execution stack are executed, they will go to the task queue to check whether asynchronous tasks are executed. Because the main thread repeatedly obtains, executes, re obtains and re executes tasks, this mechanism is called event loop.
5. location object
The window object provides us with a location attribute to get or set the url of the form, and the url can be parsed. Because this property returns an object, we also call this property location object.
5.1,url
==Uniform resource locator = = is the address of standard resources on the Internet. Every file on the Internet has a unique URL, which contains information indicating the location of the file and what the browser should do with it.
The general syntax format of url is:
protocol://host[:port]/path/[?query]#fragment http://www.itcast.cn/index.html?name=andy&age=18#link
form | explain |
protocol | Common communication protocols include http,ftp,maito, etc |
host | Host (domain name) www.itheima.com com |
port | Port number, optional |
path | A string whose path is separated by zero or more '/' symbols |
query | Parameters are in the form of key value pairs separated by the & symbol |
fragment | The content behind the clip # is common in link anchors |
5.2. location object attribute
location object properties | Return value |
location.href | Get or set the whole URL |
location.host | Return to the host (domain name) www.baidu.com com |
location.port | Returns the port number. If not written, returns an empty string |
location.pathname | Return path |
location.search | Return parameters |
location.hash | Returning the content # after the clip is common in link anchors |
Key points to remember: href and search
Requirement: jump to the page after 5s
<body> <button>click</button> <div></div> <script> var btn = document.querySelector('button'); var div = document.querySelector('div'); var timer = 5; setInterval(function() { if (timer == 0) { location.href = 'http://www.itcast.cn'; } else { div.innerHTML = 'You will be' + timer + 'Seconds later, jump to the home page'; timer--; } }, 1000); </script> </body>
5.3 location object method
location object method | Return value |
location.assign() | Like href, you can jump to a page (also known as a redirect page) |
location.replace() | Replace the current page, because the history is not recorded, so you can't go back to the page |
location.reload() | Reloading the page is equivalent to the refresh button or f5. If the parameter is true, forced refresh ctrl+f5 |
<body> <button>click</button> <script> var btn = document.querySelector('button'); btn.addEventListener('click', function() { // Record browsing history, so you can realize the back function // location.assign('http://www.itcast.cn'); // The browsing history is not recorded, so the back function cannot be realized // location.replace('http://www.itcast.cn'); location.reload(true); }) </script> </body>
5.4. Get URL parameters
We simply write a login box, click login and jump to index html
<body> <form action="index.html"> user name: <input type="text" name="uname"> <input type="submit" value="Sign in"> </form> </body>
Next we write index html
<body> <div></div> <script> console.log(location.search); // ?uname=andy // 1. First remove? substr('starting position ', intercepting several characters); var params = location.search.substr(1); // uname=andy console.log(params); // 2. Use = to divide the string into an array split('='); var arr = params.split('='); console.log(arr); // ["uname", "ANDY"] var div = document.querySelector('div'); // 3. Write data into div div.innerHTML = arr[1] + 'Welcome'; </script> </body>
In this way, we can get the URL parameters on the path
6. navigator object
The navigator object contains information about the browser and has many properties
We often use userAgent, which can return the value of the user agent header sent by the client to the server
The following front-end code can judge which terminal the user uses to open the page. If it is opened by PC, we will jump to the page on PC. if it is opened by mobile phone, we will jump to the page on mobile phone
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 = ""; //mobile phone } else { window.location.href = ""; //computer }
7. history object
The window object provides us with a history object to interact with the browser history
This object contains the URL that the user (in the browser window) has visited.
history object method | effect |
back() | Can reverse function |
forward() | Forward function |
Go (parameter) | Forward and backward function, if the parameter is 1 forward 1 page, if it is - 1 backward 1 page |
<body> <a href="list.html">Click me to go to the list page</a> <button>forward</button> <script> var btn = document.querySelector('button'); btn.addEventListener('click', function() { // history.forward(); history.go(1); }) </script> </body>