原文地址。php
咱们会常用iframes来加载第三方的内容、广告或者插件。使用iframe是由于他能够和主页面并行加载,不会阻塞主页面。固然使用iframe也是有利有弊的:Steve Souders在他的blog里面有阐述:Using Iframes Sparingly:css
阻塞主页面的onload是这两个问题中最影响性能的方面。通常都是想让onload时间越早触发越好,一方面是用户体验过更重要的是google给网站的加载速度的打分:用户能够用IE和FF中Google工具栏来计时。html
那么为了提升页面性能,怎样才能不阻塞主页面的onload事件的来加载iframe呢?web
这篇讲了四种加载iframe的方法:普通iframe,onload以后加载iframe,setTimeout() iframe和异步加载iframe。每种方法的加载结果我都用IE8的时间线来展现。我建议多注意下动态异步加载这个方法,由于这是性能表现最佳的。另外,还有一种友好iframe(friendly iframe)技术。他可能算不上是iframe加载的技术,可是必须使用iframe,他是无阻塞加载的。ajax
这是一种人尽皆知的普通加载方法,它没有浏览器的兼容性问题。浏览器
1 <iframe src="/path/to/file" frameborder="0" width="728" height="90" scrolling="auto"> </iframe>
使用这种加载方法会在各浏览器中有以下表现:app
这里是一个演示页面,时间线图显示出iframe会阻塞主页面的加载。异步
1 <script> 2 3 //doesn't block the load event 4 function createIframe() { 5 var i = document.createElement("iframe"); 6 i.src = "path/to/file"; 7 i.scrolling = "auto"; 8 i.frameborder = "0"; 9 i.width = "200px";10 i.height = "100px";11 document.getElementById("div-that-holds-the-iframe").appendChild(i);12 };13 // Check for browser support of event handling capability 14 if (window.addEventListener) window.addEventListener("load", createIframe, false);15 else if (window.attachEvent) window.attachEvent("onload", createIframe);16 else window.onload = createIframe;17 </script>
这种加载方法也是没有浏览器的兼容性问题的:async
这是是一个测试页面,时间线图以下ide
<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>