BOM (Browser Object, Single Thread)

1. BOM: Browser object, which can interact with the browser window. The core object is window.

The difference between BOM and DOM:

The DOM is a document object model. It treats a document as an object, and its top-level object is document.

BOM is a browser object model, which treats the browser as an object. Its top-level object is window.

1. Window Load Events (Page Load Events):

window.onload: is a window (page) loading event that is triggered when the document content (including images, script files, CSS files, etc.) is fully loaded and the event handler corresponding to the event is called.

The document.DOMContentLoaded:document.DOMContentLoaded load event triggers when the DOM load completes, and the load does not include the loading of additional content such as CSS stylesheets, pictures, and flash animations.

        window.onload = function(){}

        window.addEventListener('load',function(){})

<body onload="test()">
    <script>
        // window.addEventListener('load',function(){
        //     alert('Page Loading...')
        // })
        function test(){
            alert('Page Loading...')
        }
    </script>
</body>

2. Adjust Window Size Event

Window.onresize: When the window window is resized, the window.onresize event is triggered and the event handler is called.

        window.onresize = function(){}

        window.addEventListener('resize',function(){})

window.addEventListener('resize',function(){
            console.log('Window size changed')
        })

3. Timer method

(1) setTimeout(function(){}, interval): call a function or execute a piece of code after a specified number of milliseconds

        var st = setTimeout(func,1000);

Example: Countdown card

<style>
    div{
        width: 500px;
        margin: 100px auto;
        font-size: 25px;
        color: red;
    }
</style>
<body>
    <!--Countdown card: Today is 2022 New Year's Day:-day-hour-Minute-second-->
    <div></div>
    <script>
        function showTime(){
            var date1 = new Date('2022-01-01 00:00:00');
            console.log(date1)
            var date2 = new Date();

            var m = date1.getTime()-date2.getTime();
            var times = m/1000;
            var y = parseInt(times/60/60/24/31);
            var d = parseInt(times/60/60/24%30);
            var h = parseInt(times/60/60%24); h= h>=10?h:'0'+h;
            var m = parseInt(times/60%60);m= m>=10?m:'0'+m;
            var s = parseInt(times%60);s= s>=10?s:'0'+s;

            var str = y+'month'+d+'day'+h+':'+m+':'+s
            document.querySelector('div').innerHTML = str;

            setTimeout(showTime,1000)
        }
        window.onload = showTime();
    </script>
</body>

(2) setInterval(); Call a function or execute a piece of code within a specified period (in milliseconds); (more common)

[Case] Automatically close ads after 3s                                                             

<script>
       //Close ads after three seconds
    //    var timer = setTimeout(func,3000); // Execute only once
       setInterval(func,3000)   //Execute multiple times
       function func(){
           console.log('Advertisement closed...')
       }
</script>

(3) clearTimeout (timer object); Cancel timers created with setTimeout

(4) clearInterval (timer object): cancel timer created by setInterval

[Case] Text messages can only be sent once in 60 seconds     

① Place a text box and a Send button on the page.
② Enter your mobile number in the text box and click the Send button to send a text message.
③ After the button is clicked, the text on the button changes to "Left" x Second click again.                                          
<body>
    <div>
        <label>
            Phone number:
            <input type="text" name="" id="">
            <button id="btn">Send out</button>
        </label>
    </div>
    <script>
        
        //1. Get the button
        var btn = document.querySelector('#btn')
        var time = 60;//Define the number of seconds remaining
        btn.addEventListener('click',function(){
           
            btn.disabled = true;
            //Add a countdown button here
            //2. Create a timer,: setInveral
        var timer = setInterval(function(){
            if(time == 0){
                //2.1 Clear timer
                clearInterval(timer);
                //2.1 Make Buttons Available
                btn.disabled = false;
                //2.3 Make the text of the button send
                btn.innerHTML = 'Resend';
                time = 60;
            }else{
                btn.innerHTML = 'Remaining'+time+'second';
                time--;
            }
        },1000)
        })
        
    </script>
</body>

  

The difference between setTimeout and setInterval:

setTimeout: Execute once

setInterval: Repeat execution

2. Single-threaded: js programs are single-threaded and can only do one thing at a time

Synchronization: The so-called synchronization refers to the execution of a task after the completion of the previous task. The execution order of the program and the order of tasks are consistent and synchronized.

console.log(1);  //Output 1, 2 first
setTimeout(function () {
  console.log(3); //, wait 5 seconds and output 3
}, 5000);
console.log(2);

Asynchronous: Asynchronous means that you can handle other things while doing one thing.

3. js Execution Mechanism: Execution Stack, Task Queue

console.log(1);
setTimeout(function () {
  console.log(3);
}, 0);
for (var i = 0, str = ''; i < 900000; i++) {
  str += i;	 // Slow execution time using string concatenation
}
console.log(2);

3. location object: address object

1. URL: Uniform Resource Locator (URL)

(1) protocol: Network protocol. http, https, ftp, milto

(2) host: server host name (e.g. www.baidu.com)

        Name of local machine: localhost         ----> 127.0.0.1

(3) port: port number. There are 65535 port numbers, one for each service

        0~1023: used by the system, with specific services;

        1024~65535: Users can use

(4) path: the path to the page file

        http://www.souhu.com

  (5) query: query parameters. The parameters passed to the server. Use'&'between parameters

Separate, with'?'between parameters and server addresses

http://localhost:8080/getData?id = "1001" &name = "Zhang San"

2. Common attributes:

(1) location.search: Return the query part of the current URL, i.e. "?" Later part

(2) location.hash: Return the beginning of'#'in the URL

(3) location.host: Returns the host name and port number of the URL

(4) location.histname: Host name returning URL

(5) location.href: Return the full URL

<body>
    <button>Go to Baidu</button>
    <script>
        var btn = document.querySelector('button')
        btn.addEventListener('click',function(){
            location.href = "http://www.baidu.com"
            // document.location = "http://www.baidu.com"
        })
    </script>
</body>

(6) location.pathname: return path name  

(7) location.port: the port number of the return URL

(8) location.protocol: the network protocol that returns the URL

decodeURIComponent(): is a decoding function in js

[Case] Get URL parameters   

Create login.html login page:

<form action="index.html">
  User name: <input type="text" name="uname">
  <input type="submit" value="Sign in">
</form>

Create index.html home page

console.log(location.search);  //  The result is:? uname=andy
    //  1. Remove the question mark'?'from search.
    var params = location.search.substr(1);
    console.log(params); //  The result is uname=andy
    //  2. Split the string into arrays
    var arr = params.split('=');
    console.log(arr); //  The result is: ['uname',   "andy"]
    var div = document.querySelector('div');
    //  3. Write the data into the div
    div.innerHTML = arr[1] + 'Welcome';

3. Common methods4. navigator object: for navigation

1. Common attributes:

2. Common methods:

Common method javaEnabled(): Specifies whether Java is enabled in the browser.

5. history Object: history of Record Access

1. Common attributes:

history.length property: Returns the number of addresses in the history list.

2. Common methods:

Tags: Javascript Front-end OOP

Posted on Wed, 01 Dec 2021 18:57:37 -0500 by GuiltyGear