1. 历史状态管理
能够触发浏览器历史状态栈的操作,也是vue-router的实现原理
1.1 Hash
通过#
(锚点)来实现页面内定位,不会触发页面刷新
每次改变Hash
值会在浏览器状态栈中添加一条记录并触发hashchange
事件
Hash
是浏览器行为,对服务器无效,也不会被包含进HTTP
请求
1.2 History
能够在不加载新页面的情况下改变浏览器URL
API
history.back()
hsitory.forward()
hsitory.go()
pushState
:在历史状态栈中添加一条记录
replaceState
:重写当前记录
// 示例
window.onload = function () {
// 阻止页面后退
pushState ()
window.addEventListener('popstate', pushState)
};
function pushState () {
const state = {
title: 'title',
url: '#'
}
window.history.pushState(state, 'title', '#')
}
2. 高级函数
2.1 惰性载入函数
解决调用时多次if
判断的性能流失问题
使用方法:首次调用函数后,使用判断结果覆盖原函数
function createText() {
// 伪代码
if (system === 'windows') {
if (broswer === 'chrome') {
createText = function () {
return 'windows chrome'
}
}
} else if (system === 'android') {
if (device === 'Samsung') {
createText = function () {
return 'android Samsung'
}
}
}
return createText()
}
2.2 Yielding Processes
解决循环造成的脚本长时间运行
当脚本的运行不是必须同步执行且数据不是必须顺序完成时,可以使用数组分块技术进行处理
// 可以根据需求修改chunk函数的入参,实现更复杂的处理
function chunk(dataList, processFn, target) {
setTimeout(() => {
const data = dataList.shift()
processFn.call(target, data)
if (dataList.length) {
chunk(dataList, processFn, target)
}
}, 100)
}
2.3 防抖
函数连续触发时,只在停止触发后执行一次
function debounce(fn, target = this, interval = 100) {
clearTimeout(fn.tid)
fn.tid = setTimeout(() => {
fn.call(target)
}, interval)
}
2.4 节流
函数连续触发时,只在规定间隔后触发
function throttle(fn, target = this, interval = 100) {
if (!fn.isLock) {
fn.call(target)
fn.isLock = true
setTimeout(() => {
fn.isLock = false