简体   繁体   English

将JS / JavaScript代码插入父级的iframe中

[英]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. 我有一个脚本,我从我的服务器加载到我的父HTML头...我想在重新加载时将该脚本插入到我的iframe中。

I have a function that makes my iframe reload before it insert scripts into head like this:- 我有一个函数,使我的iframe重新加载之前,它将脚本插入头像这样: -

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. 这个文件是1.5 MB,每次重新加载它再次加载,我想消除。

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. 我想如果我可以从父加载它并将文件放在每次重新加载到iframe然后我可能会消除从服务器加载的文件,这将节省时间。

Any help will be appreciated 任何帮助将不胜感激

-Thanks -谢谢

JavaScript script file won't start loading until you append it to the html page. 在您将其附加到html页面之前,JavaScript脚本文件将不会开始加载。 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. 您可以在父级中加载脚本并获取代码内容并将其放在iframe中,而不是直接将带有src的脚本标记插入到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: 现在,每次iframe重新加载时,您都可以阅读其内容并将内容放在iframe脚本标记中:

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. 这样,您就可以实现您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM