Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert JS / JavaScript code into iframe from parent

I have a script which I loaded into my parent HTML head from my server... I want to insert that script into my iframe whenever it reloads.

I have a function that makes my iframe reload before it insert scripts into head like this:-

function insertScriptIntoHead(){
    var head = iframe.contentWindow.document.getElementsByTagName('head')[0];
    var script = iframe.contentWindow.document.createElement('script');
    script.src = getFromParent();
    script.type = 'text/javascript';
    head.appendChild(script);
}

This file is of 1.5 mb and upon every reload it is loaded again which I want to eliminate.

I thought if I can load it from parent and put the file on every reload into the iframe then probably I will eliminate the file getting loaded from the server which will save time.

Any help will be appreciated

-Thanks

like image 494
sidd Avatar asked Jan 29 '23 20:01

sidd


1 Answers

JavaScript script file won't start loading until you append it to the html page. You can load the script in the parent and get the code content and put it inside iframe instead of directly being inserted the script tag with src into iframe.

In parent you can load it.

<script src="bigjs.js" id="iframejs"></script>

and now you can read its content and put the content in the iframe script tag everytime that iframe reloads:

function insertScriptIntoHead(){
    var head = iframe.contentWindow.document.getElementsByTagName('head')[0];
    var script = iframe.contentWindow.document.createElement('script');
    script.innerText = document.getElementById('iframejs').innerText;
    script.type = 'text/javascript';
    head.appendChild(script);
}

This way, you can achieve what you want.

like image 140
asmmahmud Avatar answered Feb 03 '23 05:02

asmmahmud