Introduction to zero basic JavaScript-BOM (day 4)

1, BOM browser object model

1.BOM overview

1.1 what is BOM

BOM (Browser Object Model) is the Browser Object Model. It provides an object that interacts with the browser window independent of content. Its core object is window.

BOM consists of a series of related objects, and each object provides many methods and attributes.

BOM lacks standard. The standardization organization of JavaScript syntax is ECMA, and the standardization organization of DOM is W3C. BOM was originally a part of Netscape browser standard.

1.2 composition of BOM

BOM is larger than DOM, which contains dom.

window object is the top-level object of browser, which has dual roles.

1. It is an interface for JS to access the browser window.

2. 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

2. Common events of window objects

2.1 window loading events

window.onload = function(){}

perhaps

window.addEventListener("load",function(){});

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.

be careful:

1. 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.

2. window.onload the traditional registration event method can only be written once. If there are multiple events, the last window will be used Onload shall prevail.

3. If you use addEventListener, there is no limit

document.addEventListener('DOMContentLoaded',function(){})

When the DOMContentLoaded event is triggered, it is only when the DOM is loaded, excluding style sheets, pictures, flash, etc.

Ie9 and above are supported

If there are many pictures on the page, it may take a long time from user access to onload trigger, and the interaction effect cannot be realized, which will inevitably affect the user experience. At this time, DOMContentLoaded event is more appropriate.

2.2 window resizing events

 window.onresize = function(){}  

window.addEventListener("resize",function(){});

window.onresize is a processing function called when the window resizing loading event is triggered.

be careful:

1. This event will be triggered whenever the window size changes in pixels.

2. We often use this event to complete the responsive layout. window.innerWidth the width of the current screen

3. Timer

3.1 two timers

window object provides us with two very useful methods - timer.  

  • setTimeout()  
  • setInterval()  

3.2 setTimeout

 window. SetTimeout (calling function, [number of milliseconds delayed]);

The setTimeout() method is used to set a timer that executes the calling function after the timer expires.

be careful:

1. window can be omitted.

2. This calling function can directly write the function, or write the function name, or take the form of string 'function name ()'. The third is not recommended

3. The number of milliseconds delayed is omitted. The default is 0. If it is written, it must be milliseconds.

4. 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 in code order.

This function needs to wait until the time is up, so it is called a callback function.

Simple understanding: callback means to call back. After the last thing is done, call this function again later.

We talked about element Onclick = function() {} or element addEventListener(“click”, fn); The function inside is also a callback function.

Case: ads that automatically close after 5 seconds

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <img src="images/ad.jpg" alt="" class="ad">
    <script>
        var ads=document.querySelector('.ad');
        setTimeout(function(){
            ads.style.display='none';
        },5000);
    </script>
</body>
</html>

3.3 stop the setTimeout timer

 window.clearTimeout(timeoutID)

The clearTimeout() method cancels the timer previously established by calling setTimeout().

be careful:

1. window can be omitted.

2. The parameter inside is the identifier of the timer.

3.4 setInterval() timer

 window. Setinterval (callback function, [milliseconds of interval]);

setInterval() method calls a function repeatedly, and calls the callback function every other time.

be careful:

1. window can be omitted.

2. This calling function can directly write the function, or write the function name, or take the form of string 'function name ()'.

3. The number of milliseconds of the interval is omitted. The default is 0. If it is written, it must be milliseconds, which means that this function is called automatically every milliseconds.

4. Because there may be many timers, we often assign an identifier to the timer.

5. The first execution is also executed after the interval of milliseconds, and then every milliseconds.

Case: Countdown

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            margin: 200px;
        }

        span {
            display: inline-block;
            width: 40px;
            height: 40px;
            background-color: #333;
            font-size: 20px;
            color: #fff;
            text-align: center;
            line-height: 40px;
        }
    </style>
</head>

<body>
    <div>
        <span class="hour">1</span>
        <span class="minute">2</span>
        <span class="second">3</span>
    </div>
    <script>
        var hours = document.querySelector('.hour');
        var minutes = document.querySelector('.minute');
        var seconds = document.querySelector('.second');

        var inputTime = +new Date('2019-5-1 18:00:00'); // Returns the total number of milliseconds of user input time

        countDown();// Let's call this function once to prevent blank pages from being refreshed for the first time 

        // 2. Turn on the timer
        setInterval(countDown, 1000);


        function countDown() {
            var date = +new Date();
            var times = ( date-inputTime) / 1000;// times is the total number of seconds remaining 

            var h = parseInt(times / 60 / 60 % 24); //Total hours and seconds / 60 seconds / 60 minutes more than 24 hours
            h = h < 10 ? '0' + h : h;
            hours.innerHTML = h; // Give the remaining hours to the black box

            var m = parseInt(times / 60 % 60); // branch
             m = m < 10 ? '0' + m : m;
            minutes.innerHTML = m;

            var s = parseInt(times % 60); // Current seconds
            s = s < 10 ? '0' + s : s;
            seconds.innerHTML = s;


            console.log(h+':'+m+':'+s);


        }
    </script>
</body>

</html>

3.5 stop setInterval() timer

 window.clearInterval(intervalID);

The clearInterval() method cancels the timer previously established by calling setInterval().

be careful:

1. window can be omitted.

2. The parameter inside is the identifier of the timer.

Case: sending SMS

After clicking the button, the button cannot be clicked again within 60 seconds to prevent repeated sending of short messages

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    phone number: <input type="number"> <button>send out</button>
    <script>
        // After the button is clicked, disabled will be disabled and set to true 
        // At the same time, the content in the button will change. Note that the content in the button can be modified through innerHTML
        // There are changes in the number of seconds, so a timer is needed
        // Define a variable, which decreases continuously in the timer
        // If the variable is 0, it means that it is time. We need to stop the timer and restore the initial state of the button
        var ipt = document.querySelector('input');
        var but = document.querySelector('button');
        var tims = 3;
        but.addEventListener('click', function () {
            but.disabled = true;

            var timer = setInterval(function () {
                if (time == 0) {
                    // Clear timer and reset button
                    clearInterval(timer);
                    btn.disabled = false;
                    but.innerHTML = 'send out'
                } else {
                    but.innerHTML = 'Remaining' + tims + 'second';
                    tims--;
                }
            }, 1000);
        });


    </script>
</body>

</html>

3.6 this

The point of this cannot be determined when the function is defined. Only when the function is executed can we determine who this points to. Generally, this finally points to the object that calls it

At this stage, let's first understand some of this points

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)

2. Who calls this in the method call

3. this in the constructor refers to the instance of the constructor

Homework after class: clock

After class, the students make an electronic clock to display the current month, day, hour, minute and second. It is required to change automatically

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>1</div>
    <script>
        var divs=document.querySelector('div');
        setInterval(shijian, 0);    //Constantly calling refresh
      function shijian(){
            var date= new Date();
            var yer=date.getFullYear();   //year
            var moth=date.getMonth()+1;//month
            var ri=date.getDate();//day
            var day=date.getDay();//week
            var arr=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
            var h=date.getHours();//Time
            var m=date.getMinutes();//branch
            var s=date.getSeconds();//second

            var tims=yer+'year'+moth+'month'+ri+'day'+arr[day]+h+':'+m+':'+s;
          divs.innerHTML=tims;
           
        }
        shijian();
    </script>
</body>
</html>

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 before deleting.

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.1 one question

What is the result of the execution of the following code?

 console.log(1);    

setTimeout(function () {

     console.log(3);

 }, 1000);

   console.log(2);

Answer: 1,2,3

So what is the result of the following code execution?

 console.log(1);

   setTimeout(function () {

     console.log(3);  }, 0);

   console.log(2);

Answer: 1,3,2

4.2 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. The execution order of the program is consistent and synchronized with the sequence of tasks. For example, the synchronous method of Cooking: we need to boil water and cook. When the water boils (10 minutes later), we can cut and fry vegetables.

asynchronous

When you are doing something, because it will take a long time, you can deal with other things while doing it. For example, in the asynchronous method of cooking, we use this 10 minutes to cut and fry vegetables while boiling water.

Their essential difference: the execution order of each process on this pipeline is different.

4.3 synchronous and asynchronous

Synchronization task

Synchronization tasks are executed on the main thread to form an execution stack.

Asynchronous task

The asynchrony of JS is realized through callback function.

Generally speaking, there are three types of asynchronous tasks:

1. Common events, such as click, resize, etc

2. Resource loading, such as load, error, etc

3. Timer, including setInterval, setTimeout, etc

Asynchronous task related callback functions are added to the task queue (also known as message queue).

4.4 JS execution mechanism

1. Execute the synchronization task in the stack first.

2. Put the asynchronous task (callback function) into the task queue.

3. 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.

4.4 JS execution mechanism

 console.log(1);  

document.onclick = function() {

   console.log('click');  

}

 console.log(2);

 setTimeout(function() {

   console.log(3)  }, 3000)

 

Because the main thread repeatedly obtains, executes, re obtains and re executes tasks, this mechanism is called event loop.

5.location object

5.1 what is a location object

The window object provides us with a location attribute, which is used to obtain or set the URL of the form, and can be used to parse the URL. Because this property returns an object, we also call this property location object.

5.2 URL

Uniform resource locator (URL) 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

5.3 properties of location object

Key points to remember: href and search

Case: automatically jump to the page after 5 seconds

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>click</button>
    <div></div>
    <script>
        var but=document.querySelector('button');
        var divs=document.querySelector('div');
    
        but.addEventListener('click',function(){
            location.href='https://www.baidu.com/';
         
        });
        setInterval(timrr,1000);


        var tims=5;
        function timrr(){
        if(tims==0){
            location.href='https://www.baidu.com/';
        }else{
         divs.innerHTML='You will be' +tims+ 'Seconds later, jump to the home page';
          tims--;
          }
        }
       
    </script>
</body>
</html>

Method of object location

 

6.navigator object

The navigator object contains information about the browser. It has many properties. The most commonly used one is 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 of the user opens the page and realize jump

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 objects are rarely used in actual development, but they will be seen in some OA office systems.  

 

Video: Dark horse programmer JavaScript core tutorial, front-end basic tutorial, JS will be able to DOM BOM operation_ Beep beep beep_ bili bilihttps://www.bilibili.com/video/BV1k4411w7sV?p=1

This article is a self summary of my learning video. If there is any violation, please forgive me. Infringement must be deleted.

Keywords: Javascript Front-end Web Development

Added by wholein1 on Wed, 23 Feb 2022 17:29:26 +0200