Skip to content

Instantly share code, notes, and snippets.

@mark-rushakoff
Created February 27, 2012 07:01
Show Gist options
  • Save mark-rushakoff/1922091 to your computer and use it in GitHub Desktop.
Save mark-rushakoff/1922091 to your computer and use it in GitHub Desktop.
Detect data leaks in jQuery
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.7.1");
function findLeaks(jQuery) {
var cache = {};
jQuery.each(jQuery.cache, function(key, val) {
cache[key] = val;
});
jQuery("*").each(function(i, el) {
delete cache[el[jQuery.expando]];
});
return cache;
}
function jQueryIsClean(jQuery) {
ok(jQuery.isEmptyObject(findLeaks(jQuery)), "expected no leaks in jQuery cache");
}
function jQueryHasLeak(jQuery) {
ok(!jQuery.isEmptyObject(findLeaks(jQuery)), "expected leak in jQuery cache");
}
google.setOnLoadCallback(function () {
test("the default state should be clean", function() {
jQueryIsClean($);
});
test("cleaning up after a data should be clean", function() {
jQueryIsClean($);
var $div = $("<div/>");
$div.data("foo", "bar");
ok(!!$.cache[$div[0][$.expando]], "The element with data should be present in jQuery's cache");
$div.remove();
jQueryIsClean($);
});
test("it recognizes when there is a leak", function() {
jQueryIsClean($);
$("<div> <span/> </div>").find("span").data("foo", "bar");
jQueryHasLeak($);
});
});
</script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script>
</head>
<body>
<h1 id="qunit-header">QUnit example</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup, will be hidden</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment