I have one HTML page with parent.js in it. Within that html, one iFrame will be created on runtime. This iframe needs the parent.js in its context. If I am having one
function save() { ... }
in the parent.js, I can call that from iframe.js, like
parent.save();
But i need to call that in the iframe context, like
save();
So I have loaded the parent.js again in the iframe html. This makes parent.js to be loaded everytime I create a new iframe.
Is there anyway I could reuse the parent.js which is already loaded, into each iframe created?, like
loadParentJS("parent.js");
within iframe.js. This shouldn't give another request to application server.
Encapsulate your code in parent.js in a closure:
var loadParentJS = function(window) {
window.save = function() {
// code
};
window.other = function() {
// code
};
// rest of your code...
};
loadParentJS(window);
Then in your iframe, run this:
parent.loadParentJS(window);
In your parent.js file, preceed each function and variable with this. and then you should be able to take advantage of Javascript Closures.
Replace: function save() { ... }
With: this.save = function() { ... }
Replace: var aVariable = "value";
With: this.aVariable = "value";
Then in your iframe you need to set the scope of this to parent:
this = parent;
All of your calls to functions or variables in parent.js (in the global javascript or in the iframe javascript) will look like this:
this.save();
alert(this.aVariable);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With