我们先看下面的代码:
setTimeout(function(){ alert(count); },2000); var count = []; document.body.appendChild(createEditorBody()); function oninitialized(){ count.push(2); } count.push(1); function createEditorBody(){ var editorBody = createElement('div',{ 'class':'editor-body', 'html':'<iframe frameborder="0"></iframe>' }); var ifr = editorBody.querySelector('iframe'); addEvent(ifr,'load',function(){ doc = ifr.contentDocument || ifr.contentWindow.document; //页面处于正在加载的状态 //只要在doc.write()方法前后加上doc.open(), doc.close()就可以了 //IE下有权限问题 !document.all && doc.open(); doc.write('<!DOCTYPE html>\ <html>\ <head>\ <meta content="text/html; charset=utf-8" http-equiv="Content-Type">\ <link href="iframe.css" rel="stylesheet">\ </head>\ <body></body>\ </html>' ); !document.all && doc.close(); oninitialized(); }); return editorBody; }; function createElement(tag,obj){ if(typeof tag !== 'string') return; var node = document.createElement(tag), prop, value; for(prop in obj){ value = obj[prop]; if(prop === 'html') value && (node.innerHTML = value); else if(typeof value === 'function') value && addEvent(node,prop,value); else value && node.setAttribute(prop,value); } return node; }; function addEvent(el,type,fn,capture) { if (window.addEventListener) { if (type === "mousewheel" && document.mozHidden !== undefined) { type = "DOMMouseScroll"; } el.addEventListener(type, fn, capture || false); } else if (window.attachEvent) { el.attachEvent("on" + type, fn); } };
IE,火狐,运行结果为1,2
Chrome Safari Opera 运行结果为2,1
很奇怪Chrome Safari Opera环境下onload事件似乎变成了同步执行,我们都知道事件是异步的,应该是先走count.push(1); 再执行oninitialized方法 count.push(2);
原因是Chrome Safari Opera执行速度过快,导致onload事件同步执行
解决方案:
1、为iframe标签src属性指定一个不存在的页面,因为后面的doc.write会把页面重写
2、防止瞬间显示404页面,为iframe设置宽高为0,在onload事件中改为100%
代码如下:
var editorBody = createElement('div',{ 'class':'editor-body', 'html':'<iframe frameborder="0" src="iframe.html" style="width:0;height:0;"></iframe>' });
addEvent(ifr,'load',function(){ ................ ifr.style.width = '100%'; ifr.style.height = '100%'; ................ });