跨iframe动态加载JS与CSS文件的实现方案

作者:流萤时间:2026-10-28 08:01:17浏览:178

本文介绍在iframe结构中,父页面如何向子页面动态加载JS和CSS文件。通过对比jQuery的append()方法与原生JavaScript的appendChild()方法,详细解析了同步与异步加载的实现细节、代码示例及注意事项,包括如何判断脚本加载完成并执行回调函数。

iframe跨页面动态加载JS与CSS的实现方案

1、动态加载js,css文件(使用原生js和jquery)



iframe结构:


frame0(父)


frame2(子)


frame3(子)



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



*同级之间可以调用,可以通过子-父-子的方式调用同级


parent.parentFram(“这个方法在调用其他子frame”);



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="/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="/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");
} 
} 
作者最新文章