Skip to content

Instantly share code, notes, and snippets.

@stutrek
Last active October 18, 2020 22:31
Show Gist options
  • Save stutrek/9259002 to your computer and use it in GitHub Desktop.
Save stutrek/9259002 to your computer and use it in GitHub Desktop.
iframe memory test

iframe memory test

This is a simple test of memory reclamation in nested iframes. It demonstrates that setting the top level iframe's src to about:blank and removing it from the DOM is sufficient to allow the browser to reclaim all memory used in child iframes, even with different domains.

Scripts (both inline and remote), DOM elements, event listeners, timeouts, and intervals are all cleared from memory.

Usage

Add this to your hosts file:

127.0.0.1 localhost1 localhost2 localhost3 localhost4 localhost5 localhost6 localhost7 localhost8 localhost9 localhost10 localhost11

Run a simple static web server.

Load http://localhost11:\<port>/index.html in a web browser.

Open the timeline or take a heap snapshot, then type remove() in the console when you want to reclaim the memory. Note that you will have to click the garbage collection icon to see memory reclaimed in the timeline.

A CDN'd link to jQuery and an image are commented out. You can add them back to watch nothing change.

<!doctype html>
<html>
<head>
</head>
<body>
</body>
<!-- <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script> -->
<script type="text/javascript">
var number = parseInt(window.location.hostname.substr(9), 10) || 1;
// document.write('<img src="http://placekitten.com/100/10'+(number-1)+'" />');
if (window.location.hostname === 'localhost') {
var arr = [];
for( var i = 0; i < 5000000; i += 1) {
arr.push(i);
}
for( var i = 0; i < 1000; i += 1 ) {
document.body.appendChild(document.createElement('span'));
}
setInterval(function() {
var i = arr.length;
}, 10000);
setTimeout(function() {
var i = arr.length;
}, 1000000000);
document.body.addEventListener('click', function() {
var i = arr.length;
});
} else {
var iframe = document.createElement('iframe');
if (number > 1) {
iframe.src = 'http://localhost'+(number-1)+':'+window.location.port+window.location.pathname;
} else {
iframe.src = 'http://localhost:'+window.location.port+window.location.pathname;
}
for( var i = 0; i < 1000; i += 1 ) {
document.body.appendChild(document.createElement('span'));
}
iframe.onload = function() {
console.log(number);
}
setTimeout( function() {
window.document.body.appendChild(iframe);
}, 250)
}
function remove() {
iframe.onload = function() {
document.body.removeChild(iframe);
iframe.onload = null;
iframe = null;
}
iframe.src = 'about:blank';
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment