前端
wukong

前端

图片懒加载

IntersectionObserver API 监听元素是否到当前窗口的事件 isIntersecting

1
2
3
4
5
6
7
8
9
10
11
12
13
const observer = new IntersectionObserver((changes) => {
// changes: 目标元素集合
changes.forEach((change) => {
// intersectionRatio
if (change.isIntersecting) {
const img = change.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});

observer.observe(img);

或者直接用LazyLoading 属性,<img src="abc.jpg" loading="lazy" />,目前兼容性较差。

防抖与节流

clearTimeout(timer) 清除定时器,timer = null 修改timer的指向,不影响定时器

防抖(debounce)

触发高频事件后n秒内函数只会执行一次(触发最后一次事件),如果n秒内高频事件再次被触发,则重新计算时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 防抖函数
function debounce (fn, wait) {
let timer;
return function () {
if (timer) { clearTimeout(timer) }
timer = setTimeout(() => {
fn.apply(this, arguments)
}, wait);
}
}
// 高频事件停止触发后500ms 开始执行
const cld = debounce(console.log, 500)
cld(123)
cld(456)

节流(throttle)

高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function throttle (fn, wait) {
let timer;
return function () {
if (timer) return;
timer = setTimeout(() => {
timer = null
fn.apply(this, arguments)
}, wait);
}
}

// 稀释,高频事件500ms执行一次
const clt = throttle(console.log, 1000)
setInterval(() => {
clt('123')
}, 10);

数组转树结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

const flatArr = [
{ id: '0111', parentId: '011', name: '节点1-1-1' },
{ id: '011', parentId: '01', name: '节点1-1' },
{ id: '01', parentId: 0, name: '节点1' },
{ id: '02', parentId: 0, name: '节点2' },
{ id: '022', parentId: '02', name: '节点2-2' },
{ id: '023', parentId: '02', name: '节点2-3' },
{ id: '0222', parentId: '022', name: '节点2-2-2' },
{ id: '03', parentId: 0, name: '节点3' },
]

function getData (arr) {
// 利用两层filter实现
let data = arr.filter(item => {
item.children = arr.filter(e => {
return item.id === e.parentId
}) || []
// 第一层 筛选 parentId 为 0
return !item.parentId
})
return data
}
const res = getData(flatArr)
console.log('res', res)

cookie 不同端口号共享,根据同源策略cookie是区分端口,对于浏览器cookie区分域名不区分端口,可以共享。

 Comments