欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

iframe异步加载性能优化及无阻塞加载

我们会经常使用iframes来加载第三方的内容、广告或者插件。使用iframe是因为它可以和主页面并行加载,不会阻塞主页面。
  • iframe会阻塞主页面的onload事件
  • 主页面和iframe共享同一个连接池

  阻塞主页面的onload是这两个问题中最影响性能的方面。一般都是想让onload时间越早触发越好,一方面是用户体验过更重要的是google给网站的加载速度的打分:用户可以用IE和FF中Google工具栏来计时。

怎样做到iframe无阻塞加载onload?

Meebo的两个工程师(@marcuswestin and Martin Hunt)做了一个关于他们的Meebo Bar的演讲。他们使用iframe来加载一些插件,并且真正做到了无阻塞加载。对于有的开发者来说,他们的做法还比较新鲜。很赞,超级赞。

 

<script> (function(d) {
    var iframe = d.body.appendChild(d.createElement('iframe')),
    doc = iframe.contentWindow.document; 
    // style the iframe with some CSS     iframe.style.cssText ="position:absolute;width:200px;height:100px;left:0px;"; 
    doc.open().write('<body onload="'+   'var d = document;d.getElementsByTagName(\'head\')[0].'+   'appendChild(d.createElement(\'script\')).src'+'=\'\/path\/to\/file\'">');
    doc.close(); //iframe onload event happens })(document);</script>

 

神奇的地方就在<body onload="">:这个iframe一开始没有内容,所以onload会立即触发。然后你创建一个script元素,用他来加载内容、广告、插件什么的,然后再把这个script添加到HEAD中去,这样iframe内容的加载就不会阻塞主页面的onload!

原文地址:http://www.open-open.com/solution/view/1319458447249


来自  http://blog.csdn.net/fs821031547/article/details/51821095

普通分类: