内存泄漏就是内存中的变量没有回收,一直存在与内存中,造成内存的浪费的行为。常见的内存泄漏有以下5种
1. 意外的全局变量
2. 计时器和回调函数timers
3. DOM泄漏
4. js闭包
5. console
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<p id="p1">p1</p>
<!-- 内存泄漏:内存中的变量没有回收,一直存在与内存中,造成内存的浪费 -->
<script>
// 1. 意外的全局变量 这里的a就是全局变量 它是foo()内部作用域变量的引用
function foo() {
// 一个未声明变量的使用,会在全局对象中创建一个新的变量
a = "test";
console.log(a);
}
// 上面的写法等价于
// function foo() {
// window.a = "test";
// }
foo();
// 1.解决方法;清空这个变量 不过有缓存问题
a = null;
console.log(a);
</script>
<script>
// 2.解决方法:在js文件开头添加 ‘use strict',开启严格模式 不存在意外的全局变量
'use strict'
function foo() {
// 必须定义
let a = "test";
console.log(a);
}
foo()
// 这里的a变为局部变量
// console.log(a);
// 3.定时器setInterval或者setTimeout使用没有及时清理
// 定义一个叫timer的定时器
const timer=setInterval(()=>{
console.log(1);
},200)
// 清除叫timer的定时器
clearInterval(timer)
// 3. DOM泄漏
// 1)给DOM对象添加的属性是一个对象的引用
const obj={
a:1
}
// 给p1添加一个c属性 浅拷贝了对象obj给c obj变了c也跟着变化
document.getElementById('p1').c=obj
obj.d=5
console.log(document.getElementById('p1').c);
// 解决方法:在window.onload时间中加上 document.getElementById('id').c = null;
window.onload=()=>{
document.getElementById('p1').c = null;
console.log(document.getElementById('p1').c);
}
// 2)元素引用没有清理 直接删除元素
// 3)事件的绑定没有移除
const fn=()=>{
console.log(1);
}
document.getElementById('p1').addEventListener('click',fn)
removeEventListener('click',fn)
// 控制台打印的没有清除
// js闭包
// 闭包函数里面的局部变量没有销毁
</script>
</body>
</html>