Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<html>
<head>
<title>Circular references between JavaScript and DOM</title>
<script type="text/javascript">
// <![CDATA[
var obj;
window.onload = function()
{
obj = document.getElementById("DivElement");
document.getElementById("DivElement").expandoProperty = obj;
obj.bigString = new Array(1000).join(new Array(2000).join("XXXXX"));
};
// ]]>
</script>
</head>
<body>
<div id="DivElement">Div Element</div>
</body>
</html>
</html>
<html>
<head>
<title>Circular references between JavaScript and DOM</title>
<script type="text/javascript">
// <![CDATA[
function myFunction(element)
{
this.elementReference = element;
// This code forms a circular reference here
// by DOM-->JS-->DOM
element.expandoProperty = this;
}
function Leak()
{
//This code will leak
new myFunction( document.getElementById("myDiv") );
}
// ]]>
</script>
</head>
<body onload="Leak()">
<div id="myDiv"></div>
</body>
</html>
<html>
<head>
<title>Circular reference in closure</title>
<script type="text/javascript">
// <![CDATA[
window.onload = function outerFunction()
{
var obj = document.getElementById("element");
obj.onclick = function innerFunction()
{
alert("Hi! I will leak");
};
obj.bigString = new Array(1000).join(new Array(2000).join("XXXXX"));
// This is used to make the leak significant
};
// ]]>
</script>
</head>
<body>
<button id="element">Click Me</button>
</body>
</html>
<html>
<head>
<title>Circular reference in closure - FIXED</title>
<script type="text/javascript">
// <![CDATA[
window.onload = function outerFunction()
{
var obj = document.getElementById("element");
obj.onclick = function innerFunction()
{
alert("Hi! I will leak");
};
obj.bigString = new Array(1000).join(new Array(2000).join("XXXXX"));
// Fix the leak by breaking the reference
obj = null;
};
// ]]>
</script>
</head>
<body>
<button id="element">Click Me</button>
</body>
</html>
<html>
<head>
<title>Circular reference in closure - FIXED using another closure</title>
<script type="text/javascript">
// <![CDATA[
window.onload = function outerFunction()
{
var anotherObj = function innerFunction()
{
// Some logic here
alert("Hi! I have avoided the leak");
};
(function anotherInnerFunction()
{
var obj = document.getElementById("element");
obj.onclick = anotherObj;
})();
};
// ]]>
</script>
</head>
<body>
<button id="element">Click Me</button>
</body>
</html>
<html>
<head>
<title>Circular reference in closure - FIXED by avoiding the closure</title>
<script type="text/javascript">
// <![CDATA[
window.onload = function()
{
var obj = document.getElementById("element");
obj.onclick = doesNotLeak;
}
function doesNotLeak()
{
// Your Logic here
alert("Hi! I have avoided the leak");
}
// ]]>
</script>
</head>
<body>
<button id="element">Click Me</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.