Home >Web Front-end >JS Tutorial >An in-depth analysis of JavaScript advanced BOM technology

An in-depth analysis of JavaScript advanced BOM technology

WBOY
WBOYforward
2022-01-27 17:10:532280browse

This article brings you relevant knowledge about BOM in JavaScript. BOM is composed of a series of related objects, and each object provides many methods and properties. I hope it will be helpful to everyone.

An in-depth analysis of JavaScript advanced BOM technology

Directory Overview

An in-depth analysis of JavaScript advanced BOM technology

1. BOM Overview

  • BOM = Browser Object Model Browser Object Model
  • It provides objects that interact with browser windows independently of content. Its core object is window
  • BOM It is composed of a series of related objects, and each object provides many methods and attributes
  • BOM lacks standards. The standardization organization for JavaScript syntax is ECMA, the standardization organization for DOM is W3C, and BOM was originally the Netscape browser Part of the standard
##DOM treats the Treat the The top-level object of the DOM is windowDOM. The main thing to learn is to operate page elements. DOM is a W3C standard specification

1.1. The composition of BOM

An in-depth analysis of JavaScript advanced BOM technology

  • BOM is larger than DOM. It contains the DOM.

  • The window object is the top-level object of the browser, it has a dual role

  • It is the JS access to the browser window An interface

  • It is a global object. Variables and functions defined in the global scope will become the properties and methods of the window object

  • You can omit the window when calling. The dialog boxes learned earlier belong to the window object method. Such as alert(), prompt(), etc.

  • Note: A special attribute window.name under window

// 定义在全局作用域中的变量会变成window对象的属性
var num = 10;
console.log(window.num);
// 10

// 定义在全局作用域中的函数会变成window对象的方法
function fn() {
    console.log(11);
}
console.fn();
// 11

var name = 10;  //不要用这个name变量,window下有一个特殊属性window.name
console.log(window.num);

2. window object Common events

2.1. Window loading event

window.onload is a window (page) loading event. When the document content is completely loaded When the event is completed (including images, script files, CSS files, etc.), the handler function is called.

window.onload = function(){
    };// 或者window.addEventListener("load",function(){});

Note:

  • With window.onload you can write JS code above the page elements

  • Because onload waits for all the page content to be loaded before executing the processing function

  • window.onload Traditional registration event method can only be written once

  • If there are multiple, the last window.onload will prevail

  • There are no restrictions if you use addEventListener

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

Receives two parameters:

  • 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 will be triggered from the user access to onload It may take a long time

  • The interactive effect cannot be realized, which will inevitably affect the user experience. In this case, it is more appropriate to use the DOMContentLoaded event.

2.1.1. Difference

  • load and other page contents are all loaded, including page dom elements, pictures, flash, css Wait
  • DOMContentLoaded is when the DOM is loaded, and it can be executed without including images, flash css, etc. The loading speed is faster than load
<script>
    // window.onload = function() {
    //     var btn = document.querySelector('button');
    //     btn.addEventListener('click', function() {
    //         alert('点击我');
    //     })
    // }
    // window.onload = function() {
    //     alert(22);
    // }
    
    window.addEventListener('load', function() {
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            alert('点击我');
        })
    })
    window.addEventListener('load', function() {

        alert(22);
    })
    document.addEventListener('DOMContentLoaded', function() {
            alert(33);
        })
        // load 等页面内容全部加载完毕,包含页面dom元素 图片 flash  css 等等
        // DOMContentLoaded 是DOM 加载完毕,不包含图片 falsh css 等就可以执行 加载速度比 load更快一些</script>

2.2 , window resize event

window.onresize is a window resize loading event, a processing function called when triggered

window.onresize = function() {}// 或者window.addEventListener('resize',function(){});
  • As long as the window When the size changes in pixels, this event will be triggered
  • We often use this event to complete responsive layout. window.innerWidth The width of the current screen
    <script>
        window.addEventListener('load', function() {
            var p = document.querySelector('p');
            window.addEventListener('resize', function() {
                console.log(window.innerWidth);

                console.log('变化了');
                if (window.innerWidth <= 800) {
                    p.style.display = 'none';
                } else {
                    p.style.display = 'block';
                }

            })
        })
    </script>
    <p></p>

3. Timer

The window object provides us with two timers

  • setTimeout()
  • setInterval()

3.1, setTimeout() timing The

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

window.setTimeout(调用函数,[延迟的毫秒数]);

Note:

  • windowYou can omit
  • this calling function
    • You can directly write the function
    • or write the function name
    • or take the string 'function name()' (not recommended)
  • The delay in milliseconds is omitted and the default is 0. If written, it must be milliseconds
  • Because there may be many timers, we often assign an identifier to the timer
  • setTimeout() This calling function is also called callback functioncallback
  • Ordinary functions are directly in the order of the code Call, and this function needs to wait for an event. It will call this function when the event arrives, so it is called a callback function.
    <script>
        // 1. setTimeout 
        // 语法规范:  window.setTimeout(调用函数, 延时时间);
        // 1. 这个window在调用的时候可以省略
        // 2. 这个延时时间单位是毫秒 但是可以省略,如果省略默认的是0
        // 3. 这个调用函数可以直接写函数 还可以写 函数名 还有一个写法 '函数名()'
        // 4. 页面中可能有很多的定时器,我们经常给定时器加标识符 (名字)
        // setTimeout(function() {
        //     console.log('时间到了');

        // }, 2000);
        function callback() {
            console.log('爆炸了');

        }
        var timer1 = setTimeout(callback, 3000);
        var timer2 = setTimeout(callback, 5000);
        // setTimeout('callback()', 3000); // 我们不提倡这个写法
    </script>

3.2. clearTimeout() stops the timer

  • clearTimeout()The method cancels the previous callsetTimeout()Created timer
window.clearTimeout(timeoutID)

Note:

  • ##windowcan be omitted
  • The parameter inside is the identifier of the timer
    <button>点击停止定时器</button>
    <script>
        var btn = document.querySelector('button');
        var timer = setTimeout(function() {
            console.log('爆炸了');
        }, 5000);
        btn.addEventListener('click', function() {
            clearTimeout(timer);
        })
    </script>

3.3, setInterval() timer

  • setInterval() The method repeatedly calls a function, and every time, calls the callback function
window.setInterval(回调函数,[间隔的毫秒数]);
  • windowYou can omit this callback
  • Function:
    • You can directly write the function
    • or write the function name
    • or take the characters 'function name ()'
  • An execution is also executed after an interval of milliseconds, and then executed every millisecond
    <script>
        // 1. setInterval 
        // 语法规范:  window.setInterval(调用函数, 延时时间);
        setInterval(function() {
            console.log('继续输出');

        }, 1000);
        // 2. setTimeout  延时时间到了,就去调用这个回调函数,只调用一次 就结束了这个定时器
        // 3. setInterval  每隔这个延时时间,就去调用这个回调函数,会调用很多次,重复调用这个函数
    </script>

3.4. clearInterval() stops the timer

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

Note:

  • window可以省略
  • 里面的参数就是定时器的标识符
    <button>开启定时器</button>
    <button>停止定时器</button>
    <script>
        var begin = document.querySelector('.begin');
        var stop = document.querySelector('.stop');
        var timer = null; // 全局变量  null是一个空对象
        begin.addEventListener('click', function() {
            timer = setInterval(function() {
                console.log('ni hao ma');

            }, 1000);
        })
        stop.addEventListener('click', function() {
            clearInterval(timer);
        })
    </script>

3.5、this指向

  • this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁

现阶段,我们先了解一下几个this指向

  • 全局作用域或者普通函数中this指向全局对象window(注意定时器里面的this指向window)
  • 方法调用中谁调用this指向谁
  • 构造函数中this指向构造函数实例
    <button>点击</button>
    <script>
        // this 指向问题 一般情况下this的最终指向的是那个调用它的对象

        // 1. 全局作用域或者普通函数中this指向全局对象window( 注意定时器里面的this指向window)
        console.log(this);

        function fn() {
            console.log(this);

        }
        window.fn();
        window.setTimeout(function() {
            console.log(this);

        }, 1000);
        // 2. 方法调用中谁调用this指向谁
        var o = {
            sayHi: function() {
                console.log(this); // this指向的是 o 这个对象

            }
        }
        o.sayHi();
        var btn = document.querySelector('button');
        // btn.onclick = function() {
        //     console.log(this); // this指向的是btn这个按钮对象

        // }
        btn.addEventListener('click', function() {
                console.log(this); // this指向的是btn这个按钮对象

            })
            // 3. 构造函数中this指向构造函数的实例
        function Fun() {
            console.log(this); // this 指向的是fun 实例对象

        }
        var fun = new Fun();
    </script>

4、JS执行机制

4.1、JS是单线程

  • JavaScript 语言的一大特点就是单线程,也就是说,同一个时间只能做一件事。这是因为 Javascript 这门脚本语言诞生的使命所致——JavaScript 是为处理页面中用户的交互,以及操作 DOM 而诞生的。比如我们对某个 DOM 元素进行添加和删除操作,不能同时进行。 应该先进行添加,之后再删除。
  • 单线程就意味着,所有任务需要排队,前一个任务结束,才会执行后一个任务。这样所导致的问题是: 如果 JS 执行的时间过长,这样就会造成页面的渲染不连贯,导致页面渲染加载阻塞的感觉。

4.2、一个问题

以下代码执行的结果是什么?

console.log(1);setTimeout(function() {
    console.log(3);},1000);console.log(2);

那么以下代码执行的结果又是什么?

console.log(1);setTimeout(function() {
    console.log(3);},0);console.log(2);

4.3、同步和异步

  • 为了解决这个问题,利用多核 CPU 的计算能力,HTML5 提出 Web Worker 标准,允许 JavaScript 脚本创建多个线程
  • 于是,JS 中出现了同步和异步。
  • 同步:
    • 前一个任务结束后再执行后一个任务
  • 异步
    • 在做这件事的同时,你还可以去处理其他事情

同步任务

  • 同步任务都在主线程上执行,形成一个执行栈

异步任务

  • JS中的异步是通过回调函数实现的
  • 异步任务有以下三种类型
    • 普通事件,如click,resize
    • 资源加载,如load,error
    • 定时器,包括setInterval,setTimeout
  • 异步任务相关回调函数添加到任务队列

An in-depth analysis of JavaScript advanced BOM technology

  1. 先执行执行栈中的同步任务
  2. 异步任务(回调函数)放入任务队列中
  3. 一旦执行栈中的所有同步任务执行完毕,系统就会按次序读取任务队列中的异步任务,于是被读取的异步任务结束等待状态,进入执行栈,开始执行

An in-depth analysis of JavaScript advanced BOM technology

此时再来看我们刚才的问题:

console.log(1);setTimeout(function() {
    console.log(3);},1000);console.log(2);
  • 执行的结果和顺序为 1、2、3
console.log(1);setTimeout(function() {
    console.log(3);},0);console.log(2);
  • 执行的结果和顺序为 1、2、3
// 3. 第三个问题console.log(1);document.onclick = function() {
    console.log('click');}console.log(2);setTimeout(function() {
    console.log(3)}, 3000)

An in-depth analysis of JavaScript advanced BOM technology

同步任务放在执行栈中执行,异步任务由异步进程处理放到任务队列中,执行栈中的任务执行完毕会去任务队列中查看是否有异步任务执行,由于主线程不断的重复获得任务、执行任务、再获取任务、再执行,所以这种机制被称为事件循环( event loop)。

5、location对象

  • window 对象给我们提供了一个 location属性用于获取或者设置窗体的url,并且可以解析url。因为这个属性返回的是一个对象,所以我们将这个属性也称为 location 对象。

5.1、url

==统一资源定位符(uniform resouce locator)==是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的 URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它。

url 的一般语法格式为:

protocol://host[:port]/path/[?query]#fragment

http://www.itcast.cn/index.html?name=andy&age=18#link
DOM BOM
Document Object Model Browser Object Model
document as a object browser as a object
document## The top-level object of #BOM is
BOM is to learn some objects for browser window interaction.
BOM is defined by browser manufacturers on their respective browsers, and has poor compatibility
组成 说明
protocol 通信协议 常用的http,ftp,maito等
host 主机(域名) www.itheima.com
port 端口号,可选
path 路径 由零或多个'/'符号隔开的字符串
query 参数 以键值对的形式,通过&符号分隔开来
fragment 片段 #后面内容 常见于链接 锚点

5.2、location对象属性

location对象属性 返回值
location.href 获取或者设置整个URL
location.host 返回主机(域名)www.baidu.com
location.port 返回端口号,如果未写返回空字符串
location.pathname 返回路径
location.search 返回参数
location.hash 返回片段 #后面内容常见于链接 锚点

重点记住:hrefsearch

需求:5s之后跳转页面

    <button>点击</button>
    <p></p>
    <script>
        var btn = document.querySelector('button');
        var p = document.querySelector('p');
        var timer = 5;
        setInterval(function() {
            if (timer == 0) {
                location.href = 'http://www.itcast.cn';
            } else {
                p.innerHTML = '您将在' + timer + '秒钟之后跳转到首页';
                timer--;
            }

        }, 1000);
    </script>

5.3、location对象方法

location对象方法 返回值
location.assign() 跟href一样,可以跳转页面(也称为重定向页面)
location.replace() 替换当前页面,因为不记录历史,所以不能后退页面
location.reload() 重新加载页面,相当于刷新按钮或者 f5 ,如果参数为true 强制刷新 ctrl+f5
    <button>点击</button>
    <script>
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            // 记录浏览历史,所以可以实现后退功能
            // location.assign('http://www.itcast.cn');
            // 不记录浏览历史,所以不可以实现后退功能
            // location.replace('http://www.itcast.cn');
            location.reload(true);
        })
    </script>

5.4、获取URL参数

我们简单写一个登录框,点击登录跳转到 index.html

    
        用户名:               

接下来我们写 index.html

    <p></p>
    <script>
        console.log(location.search); // ?uname=andy
        // 1.先去掉?  substr('起始的位置',截取几个字符);
        var params = location.search.substr(1); // uname=andy
        console.log(params);
        // 2. 利用=把字符串分割为数组 split('=');
        var arr = params.split('=');
        console.log(arr); // ["uname", "ANDY"]
        var p = document.querySelector('p');
        // 3.把数据写入p中
        p.innerHTML = arr[1] + '欢迎您';
    </script>

这样我们就能获取到路径上的URL参数

6、navigator对象

  • navigator 对象包含有关浏览器的信息,它有很多属性
  • 我们常用的是userAgent,该属性可以返回由客户机发送服务器的user-agent头部的值

下面前端代码可以判断用户是用哪个终端打开页面的,如果是用 PC 打开的,我们就跳转到 PC 端的页面,如果是用手机打开的,就跳转到手机端页面

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 = "";     //电脑
 }

7、history对象

  • window 对象给我们提供了一个 history 对象,与浏览器历史记录进行交互
  • 该对象包含用户(在浏览器窗口中)访问过的 URL。
history对象方法 作用
back() 可以后退功能
forward() 前进功能
go(参数) 前进后退功能,参数如果是 1 前进1个页面 如果是 -1 后退1个页面
    <a>点击我去往列表页</a>
    <button>前进</button>
    <script>
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            // history.forward();
            history.go(1);
        })
    </script>

相关推荐:javascript学习教程

The above is the detailed content of An in-depth analysis of JavaScript advanced BOM technology. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete