5

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

3
  • do you have a question? or a problem? some error message perhaps? as it stands you've stated what you've done, but no indication of any problems Commented Aug 9, 2017 at 9:54
  • read carefully..... how to create that getFromParent() function..... Commented Aug 9, 2017 at 17:09
  • Really? I didn't get that at all, I thought that was a funciton you'd already written Commented Aug 9, 2017 at 21:16

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

... And OP was never heard from again :\

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.