The phenomenon of
The memory usage is high, causing the page to freeze and no response to a click. A memory leak is a failure to release memory that is no longer needed by system processes.
Cause of memory leak
The global variable
In browsers, global objects are window objects, and variables are not released until the window closes or the page is refreshed. If undeclared variables cache a large amount of data, they can cause a memory leak.
- Undeclared variable
function fn(){
a = 'global test'
}
fn()
Copy the code
- Variables created using this (this refers to window)
function fn(){
this.a = 'global test'
}
fn()
Copy the code
- Solutions:
1. Avoid creating global variables
2. In strict mode, add use strict to the top of the js file header or function
Memory leaks caused by closures
Reason: Closures can read variables inside functions and keep them in memory at all times. If local variables are not cleaned up at the end of use, memory leaks can result.
No DOM element references are cleared
- Solutions:
Removed manually
elements.btn = null
Forgotten timer or callback
- Solutions:
Manually delete the timer and DOM
RemoveEventlistener Removes event listening
ES6 prevents memory leaks
- Weakmap data structure, references to values are not counted in the garbage collection mechanism
const wm = new WeakMap()
const ele = document.getElementById('example')
wm.set(element,'something')
wm.get(element
Copy the code