Dynamic loading of js CSS and other files across the iframe implementation

  • 2020-03-30 02:06:25
  • OfStack

1. Load js and CSS files dynamically (with native js and jquery)

The iframe structure:
Frame0 (parent)
Frame2 (child)
Frame3 (child)

Frame2 triggers events, dynamically loads js, CSS files, and dom elements onto frame3?

* you can call between siblings, and you can call siblings as a child - parent - child
ParentFram (" this method is calling another child farme ");

1. The jquery append ()
 
 Fast, synchronous (need to be introduced 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(); //Call the test() method in frame3_id

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Above examples: a. Need to introduce jquery;
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2. Js the appendChild ()

Slow, asynchronous (need to determine whether js is loaded)

Example 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 Similar)  
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(); //The test() method is in the incoming js file
}else{ 
console.info("can not load the oScript2.js file"); 
} 
} 

Related articles: