当前位置: 代码迷 >> Web前端 >> iframe加载技术跟性能
  详细解决方案

iframe加载技术跟性能

热度:191   发布时间:2012-09-03 09:48:39.0
iframe加载技术和性能

1. 普通的Iframe

?

代码:
<iframe src=”/path/to/file” frameborder=”0″ width=”728″ height=”90″ scrolling=”auto”> </iframe>

- iframe 在主页面之前加载
- iframe 要等所有内容下载完,才开始启动
- 主页面在iframe全部完成后,才开始加载。阻塞!阻塞!!
- 当iframe加载的时候,页面一直显示繁忙指示器。

?

2. iframe在主页面之后加载

代码:
<script>?
//doesn’t block the load event?
function createIframe(){?
var i = document.createElement(“iframe”);?
i.src = “path/to/file”;?
i.scrolling = “auto”;?
i.frameborder = “0″;?
i.width = “200px”;?
i.height = “100px”;?
document.getElementById(“div-that-holds-the-iframe”).appendChild(i);?
};

// Check for browser support of event handling capability?
if (window.addEventListener)?
window.addEventListener(“load”, createIframe, false);?
else if (window.attachEvent)?
window.attachEvent(“onload”, createIframe);?
else window.onload = createIframe;

</script>

- iframe 在主页面完成加载后,才开始加载
- 主页面加载的时候,没有被iframe干扰
- 繁忙指示器依然存在。这是不好的地方。

?

3. 使用iframe setTimeout() 方法

因为对IE8无效,实际应用意义不大,在此略去

?

4. 采用动态异步调用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>

?

效果:
- iframe 在主页面之前开始加载
- iframe 在iframe的内容下载完就开始启动
- 主页面加载不受iframe影响
- 当iframe加载时,繁忙指示器消失了!

?

结论:

1. 因为iframe耗用比较多资源,做优化处理的时候又比较麻烦,尽量别采用。

2. 如果一定要用,推荐采用动态异步调用。无论是主页面加载时间,还是繁忙指示器的用户体验都有较好提升。

?

翻译自:Aaron Peters的博客

  相关解决方案