网络编程 
首页 > 网络编程 > 浏览文章

动态加载js、css等文件跨iframe实现

(编辑:jimmy 日期: 2025/12/28 浏览:3 次 )
1、动态加载js,css文件(用原生js和jquery)

iframe结构:
frame0(父)
frame2(子)
frame3(子)

frame2中触发事件,动态的向frame3中 加载js、css文件和 dom元素?

*同级之间可以调用,可以 通过 子-父-子 的方式调用同级
parent.parentFram(“这个方法在调用其他子farme”);

1.jquery的append()
复制代码 代码如下:
速度快,同步(需要引入jquery)

var oBody = document.getElementById("frame3_id").contentWindow.$("body");

var str = "<div>...</div>"
var scriptTag = document.getElementById("frame3_id").contentWindow.document.getElementById("pop");
if(!scriptTag){
oBody.append(str);
}

var oScript= document.createElement("script");
oScript.id = "oScript1";
oScript.type = "text/javascript";
oScript.src="/UploadFiles/2021-04-02/test.js">var oTag1 = document.getElementById("frame3_id").contentWindow.document.getElementById("oScript1");
if(!oTag1){
oBody.append(oScript);
}

document.getElementById("frame3_id").contentWindow.test(); // 调用frame3_id 中的test()方法

***********************************
上述例子:a.需要引入jquery;
***********************************
2.js 的appendChild()

速度慢,异步(需要判断js是否加载完毕)

列子2:
复制代码 代码如下:
var str = "<div>...</div>"
var popDiv=document.createElement('div');
popDiv.style.xx = xxx;
popDiv.id = "pop";
popDiv.innerHTML = str;
var oBody = document.getElementById("frame3_id").contentWindow.document.getElementsByTagName("body")[0];
var oHead = document.getElementById("frame3_id").contentWindow.document.getElementsByTagName("head");

if(oHead && oHead.length){
oHead = oHead[0];
}else{
oHead = oBody;
}

var elemDivTag = document.getElementById("frame3_id").contentWindow.document.getElementById("pop");
if(!elemDivTag){
oBody.appendChild(popDiv)
}

var oScript= document.createElement("script"); (css类似)
oScript.id = "oScript1";
oScript.type = "text/javascript";
oScript.src="/UploadFiles/2021-04-02/test.js">var scriptTag = document.getElementById("main").contentWindow.document.getElementById("oScript1");
if(!scriptTag){
oHead.appendChild(oScript);
}
oScript.onload = oScript.onreadystatechange = function(){
if ((!this.readyState) || this.readyState == "complete" || this.readyState == "loaded" ){
document.getElementById("main").contentWindow.test(); // test()方法 在 引入的js文件中
}else{
console.info("can not load the oScript2.js file");
}
}
上一篇:JSONP获取Twitter和Facebook文章数的具体步骤
下一篇:js操纵dom生成下拉列表框的方法
一句话新闻
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap