Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说浏览器对象详解,希望能够帮助你!!!。
提供当前窗口中的加载的文档有关的信息和一些导航功能。 既是 window 对象属性,也是 document 的对象属性
window.location === document.location; //true
// https://www.zhihu.com/search?type=content&q=123
location.href =
'https://www.zhihu.com/search?type=content&q=123'.origin = // 完整的url
'https://www.zhihu.com'.host = // 页面的标准域名
'www.zhihu.com'.hash = // 服务器名称+端口 例如:‘www.zhihu.com:8080’
'#hash'.pathname = // url中#号后面的哈希值
'/search'.search = // url中[/]后面内容
'?type=content&q=123'.protocol = // url中[?]后面内容
'https:'.port = // 协议[http:]
''; //端口号:[ 80 | 8080 | ... ]
方法:
history.state.length; // 当前页面的状态 // 返回当前 `会话` 中的 history 个数
方法:
相关联的方法
例子:
window.onpopstate = function (event) {
alert(
'location: ' +
document.location +
', state: ' +
JSON.stringify(event.state),
);
};
//绑定事件处理函数.
history.pushState({ page: 1 }, 'title 1', '?page=1'); //添加并激活一个历史记录条目 http://example.com/example.html?page=1,条目索引为1
history.pushState({ page: 2 }, 'title 2', '?page=2'); //添加并激活一个历史记录条目 http://example.com/example.html?page=2,条目索引为2
history.replaceState({ page: 3 }, 'title 3', '?page=3'); //修改当前激活的历史记录条目 http://ex..?page=2 变为 http://ex..?page=3,条目索引为3
history.back(); // 弹出 "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // 弹出 "location: http://example.com/example.html, state: null
history.go(2); // 弹出 "location: http://example.com/example.html?page=3, state: {"page":3}
浏览器系统信息大集合
用来表示浏览器窗口外部的显示器的信息等
window.screen.deviceXDPI/deviceYDPI 屏幕实际的水平 DPI、垂直 DPI
浏览器事件模型主要分为三个阶段:
el.addEventListener(event, function, useCapture)
// useCapture默认值false,也就是默认冒泡
// true为捕获阶段
{
/*
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
*/
}
var list = document.querySelector('list');
function onClick(e) {
var e = e || window.event;
if (e.target.tagName.toLowerCase() === 'li') {
// 业务逻辑...
e.target.style.backgroundColor = 'pink';
}
}
list.addEventListener('click', onClick, false);
先区别 IE 的不同之处
class BindEvent {
constructor(el) {
this.el = el;
}
addEventListener(type, handler) {
if (this.el.addEventListener) {
this.el.addEventListener(type, handler, false);
} else if (this.el.attachEvent) {
this.el.attachEvent('on' + type, handler);
} else {
this.el['on' + type] = handler;
}
}
removeEventListener(type, handler) {
if (this.el.removeEventListener) {
this.el.removeEventListener(type, handler, false);
} else if (this.el.detachEvent) {
this.el.detachEvent('on' + type, handler);
} else {
this.el['on' + type] = null;
}
}
static stopPropagation() {
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}
static preventDefault() {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
封装 XMLHttpRequest 请求
function ajax({ method = 'get', url = '', params = undefined }) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
if (method.toLowerCase() === 'get' && params !== undefined) {
url = url + '?' + params;
}
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(xhr.status);
}
}
};
if (method.toLocaleLowerCase() === 'get') {
xhr.send();
} else {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
}
xhr.onerror = (err) => reject(err);
xhr.timeout = () => reject('timeout');
// progress事件可以报告长时间运行的文件上传
xhr.upload.onprogress = (p) => {
console.log(Math.round((p.loaded / p.total) * 100) + '%');
};
});
}
// resolve若发生在网络通信正常(404,500)也是resolve
fetch('http://domain/service', {
method: 'GET',
})
.then((response) => {
// 想要精确的判断 fetch是否成功
// 需要包含 promise resolved 的情况,此时再判断 response.ok是不是为 true
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
})
.then((json) => console.log(json))
// .catch()也不会被执行
.catch((error) => console.error('error:', error));
// ************************************
// 不支持直接设置超时, 可以用promise
function fetchTimeout(url, init, timeout = 3000) {
return new Promise((resolve, reject) => {
fetch(url, init).then(resolve).catch(reject);
setTimeout(reject, timeout);
});
}
// ************************************
// 中止fetch
// signal用于支持AbortController中断请求
const controller = new AbortController();
// AbortController接口表示一个控制器对象
// 允许你根据需要中止一个或多个 Web请求
fetch('http://domain/service', {
method: 'GET',
signal: controller.signal,
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.error('Error:', error));
controller.abort();
100 信息性|200 成功|300 重定向|400 客户端错误|500 服务器错误
const request = (url) => {
let resolved = false;
let t = 1;
return new Promise((resolve, reject) => {
// Promise.race([
// fetch(url),
// wait(100, () => fetch(url)),
// wait(200, () => fetch(url)),
// wait(400, () => fetch(url)),
// wait(800, () => fetch(url)),
// wait(1600, () => fetch(url)),
// ])
function doFetch() {
if (resolved || t > 16) return;
fetch(url)
.then((resp) => resp.text())
.then((data) => {
if (!resolved) {
resolved = true;
resolve(data);
}
});
setTimeout(() => {
doFetch();
t *= 2;
}, t * 100);
}
doFetch();
});
};
import fetch from 'node-fetch';
function hash(...args) {
return args.join(',');
}
function window_it(fn, time = 50) {
let w = {}; // 时间窗口
let flag = false;
return (...args) => {
return new Promise((resolve, reject) => {
if (!w[hash(args)]) {
w[hash(args)] = {
resolves: [],
func: fn,
args,
};
}
if (!flag) {
flag = true;
setTimeout(() => {
Object.keys(w).forEach((key) => {
console.log(`run ${key}`);
const { func, args, resolves } = w[key];
func(...args)
.then((res) => res.text())
.then((data) => {
resolves.forEach((r) => {
console.log(`resolve ${key}`);
r(data);
});
flag = false;
delete w[key];
});
});
}, time);
}
w[hash(args)].resolves.push(resolve);
});
};
}
const request = window_it(fetch, 20);
request('http://www.baidu.com').then((txt) => console.log(txt.length));
request('http://www.baidu.com').then((txt) => console.log(txt.length));
request('http://www.baidu.com').then((txt) => console.log(txt.length));
request('http://www.zhihu.com').then((txt) => console.log(txt.length));
request('http://www.zhihu.com').then((txt) => console.log(txt.length));
request('http://www.zhihu.com').then((txt) => console.log(txt.length));
今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
上一篇
已是最后文章
下一篇
已是最新文章