日期:2014-05-17 浏览次数:20803 次
function loadScript(url, callback,targetWin) { if(!targetWin) targetWin = self; var script = targetWin.document.createElement("script") script.type = "text/javascript"; if (script.readyState) { // IE script.onreadystatechange = function() { if (script.readyState == "loaded" || script.readyState == "complete") { script.onreadystatechange = null; if(typeof callback == "function") targetWin.callback(); } }; } else { // Others script.onload = function() { if(typeof callback == "function") targetWin.callback(); }; } script.src = url; targetWin.document.getElementsByTagName("head")[0].appendChild(script); } //示例 function init(){ var flexWin = top.frames['flex']; var url = "/web/test.js"; if(window.addEventListener){ flexWin.addEventListener('load',function(){ loadScript(url,null,flexWin); },false); }else if(window.attachEvent){ window.attachEvent('onload',function(){ loadScript(url,null,flexWin); }); }else{ flexWin.onload =function(){ loadScript('test.js',null,flexWin); } } } /* * 注意:frame中window对象的获取,需要采用上述形式。 如果使用 document.getElementsByTagName 或 getElementById 方法,拿到的是一个frame对象,通过该frame对象,我们可以通过 contentWindow来获取对应的window对象。但是,chrome不支持 contentWindow属性。 var frames = top.document.getElementsByTagName("frame"); alert(frames['a1'].contentWindow);//undefined in chrome */
//动态加载js、css内容,直接写入页面: 动态添加js/CSS的内容在页面上: function loadScriptString(code){ var script = document.createElement("script"); script.type = "text/javascript"; try { script.appendChild(document.createTextNode(code)); } catch (ex){ script.text = code; // IE } document.body.appendChild(script); } function loadStyleString(css){ var style = document.createElement("style"); style.type = "text/css"; try{ style.appendChild(document.createTextNode(css)); } catch (ex){ style.styleSheet.cssText = css; //IE } var head = document.getElementsByTagName("head")[0]; head.appendChild(style); } Usage: loadScriptString('function sayHi(){alert("hi");}'); loadStyleString('body{background-color:red}');