我最近会去关注这个,主要是因为前端跨域问题引起的。因为在处理问卷系统的过程中,主域和子域之间的跨域问题,是通过iframe 进行处理的,标准浏览器加载iframe都没问题,但是ie下iframe加载总是会题型crossdomain未定义,第二次刷新之后,才正常和服务端 通讯。iframe的加载方式可以有(普通iframe,onload之后加载iframe,setTimeout() iframe和异步加载iframe)。
iframe加载的原理和几种方式:
一、普通加载iframe(没有兼容性问题)
<iframe src="" frameborder="0" width="728" height="90" scrolling="auto"></iframe>
这种方式在各浏览器的表现形式:
(1)iframe会在主页面的onload之前加载
(2)iframe会在所有的iframe的内容都加载完后才出发的iframe的onload事件
(3)主页面的onload事件会在页面上的所有iframe的onload触发完之后才触发,所以会阻塞主页面的加载
(4)当iframe在加载的过程中,浏览器的标识会显示正在加载东西,处于忙碌状态
二、在onload之后加载iframe(没有兼容性问题)
<script>
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);
};
if (window.addEventListener) window.addEventListener("load", createIframe, false);
else if (window.attachEvent) window.attachEvent("onload", createIframe);
else window.onload = createIframe;
</script>
这种方式的表现:
(1)iframe会在主页面onload之后加载 (2)主页面的onload事件与ifame无关,所以iframe不会阻塞主页面的加载 (3)当iframe加载的时候,浏览器会标识正在加载
这种方式比普通加载方式的好处有两点:
(1)其他页面等待主页面onload事件的代码可以尽早执行 (2)Google Toolbar计算页面加载的时间会大大减少
这种方式比普通加载方式的不好之处有两点:
(1)iframe还在加载的时候,浏览器还是处于忙碌状态,相对于普通加载方法,用户看到忙碌状态的时间更长 (2)用户还没等到页面完全加载完就离开了。比如广告
###三、setTimeout()来加载iframe
<iframe id="iframe1" src="" width="200" height="100" border="2"></iframe>
<script>
function setIframeSrc() {
var s = "path/to/file";
var iframe1 = document.getElementById('iframe1');
if ( - 1 == navigator.userAgent.indexOf("MSIE")) {
//iframe1.src = s;
} else {
// iframe1.location = s;
}
}
setTimeout(setIframeSrc, 5);
</script>
此种方法在除了ie8之外的在其他浏览器的表现:
(1)iframe会在主页面onload之前开始加载
(2)iframe的onload事件会在iframe的内容都加载完之后触发
(3)iframe不会阻塞主页面的onlaod事件(IE8除外),为什么不会阻塞,因为是使用setTimeout()
(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>
这种方式的好处:
(1)iframe会在主页面onload之前开始加载
(2)iframe的onload会立即触发,因为iframe的内容一开始为空
(3)主页面的onload不会被阻塞
(4)为什么这个iframe不会阻塞主页面的onload,因为使用了body onload
(5)如果不在iframe使用onlaod监听,那么iframe的加载就会阻塞主页面的onload
(6)当iframe加载的时候,浏览器终于不显示忙碌状态了
iframe的自适应高度
http://spd8080.blog.163.com/blog/static/174799856201342495456885/
iframe onload事件的跨浏览器
http://m.oschina.net/blog/32300
http://www.cnblogs.com/chencidi/archive/2011/03/29/1999129.html