原文地址。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>