How does an iframe dynamically create and free up memory

  • 2020-03-30 03:49:51
  • OfStack

I recently worked on a project that made a lot of calls to iframes on pages because the project was a browser-based fat client (RIA) application. Later tests found that browser memory remained high, and the more iframe pages opened, the more memory was consumed, especially in the IE family of browsers. All open iframe pages did not show a significant decline in memory usage even after closing, IE became stuck around 400M in memory usage. The analysis found that it was caused by the non-release of iframe, so the memory occupied by all closed iframes was released. Although it could not be completely released, the memory consumption of iframe would not keep growing, and the memory usage of the whole application was controlled at about 150M.


 
function createIframe(dom, src, onload){ 
//Create an iframe in the document
var iframe = document.createElement("iframe"); 

//Sets the style of the iframe
iframe.style.width = '100%'; 
iframe.style.height = '100%'; 
iframe.style.margin = '0'; 
iframe.style.padding = '0'; 
iframe.style.overflow = 'hidden'; 
iframe.style.border = 'none'; 

//Bind the onload event of the iframe
if(onload && Object.prototype.toString.call(onload) === '[object Function]'){ 
if(iframe.attachEvent){ 
iframe.attachEvent('onload', onload); 
}else if(iframe.addEventListener){ 
iframe.addEventListener('load', onload); 
}else{ 
iframe.onload = onload; 
} 
} 

iframe.src = src; 
//Load the iframe under the dom
dom.appendChild(iframe); 
return iframe; 
} 

 
function destroyIframe(iframe){ 
//Point the iframe at the blank page, which frees up most of the memory.
iframe.src = 'about:blank'; 
try{ 
iframe.contentWindow.document.write(''); 
iframe.contentWindow.document.clear(); 
}catch(e){} 
//Remove the iframe from the page
iframe.parentNode.removeChild(iframe); 
}


Related articles: