javascript - 将脚本/样式从 DOM 传递到子 iFrame

标签 javascript html

在我的服务器上,我正在渲染所有具有完全相同的脚本/样式标签的页面(来自后端的模板)。

每当我想在网站上创建一个弹出窗口时,我都会使用 src 创建一个带有 iFrame 的模态框。放。

这会导致所有脚本标签第二次加载到客户端,预期性能影响。

我的目标是让主 DOM 的脚本文件可以从 iFrame 中访问,而无需重新加载它们。

理想情况下,我能做的是将一个参数传递给服务器,告诉它不要在呈现的 HTML 中包含脚本标签,然后将这些脚本和样式从客户端直接“推送”到 iFrame 中。

我可以在哪里维护 document.ready 的功能?和其他 API,而不必从服务器重新加载所有脚本和样式?

最佳答案

My goal is to have the scripts files for the main DOM to be accessible from within the iFrame without reloading them.

Kindly note that it is not recommended due to security reasons. It is better to reload the contents or make use of AJAX (which, of course loads the content) as @Pavan said. But, to answer the question, here is my approach


一旦你加载了你的 DOM(有内联脚本和样式),你可以做
window.onload = function() {
    let styleTags = [ ...document.getElementsByTagName('style') ];
    styleText = styleTags.map(eachStyle => eachStyle.outerHTML).join('');
    // mapping each style tag to simple html text

    let scriptTags = [ ...document.getElementsByTagName('script') ];
    scriptText = scriptTags.map(eachScript => eachScript.outerHTML).join('');

    let myIFrame = document.getElementById("myIFrame");
    let doc = myiFrame.contentDocument;
    doc.body.innerHTML += styleText + scriptText;
}

This is only applicable as far as your DOM and iFrame has same domain. I expect you've the same domain for them, by default. Also, external scripts can't be accessed using this approach, they've to be loaded each time.

关于javascript - 将脚本/样式从 DOM 传递到子 iFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61015867/

相关文章:

Javascript 复选框切换问题

javascript - 根据一天中的时间和一周中的某一天更改背景?

javascript - 对于 Javascript 游戏引擎,重新使用全局变量比制作本地变量更有效还是更不有效?

javascript - 第一个文件类型预览图像显示在第二个文件类型上

javascript - 在链接后执行 "thanks_for_downloading.html"+ "Save file..."的标准方法?

html - 将 div 推到居中且响应迅速的 Bootstrap 容器元素旁边

javascript - 无需外部 API 调用的验证码

javascript - 您可以使用 Puppeteer 在提示框的文本字段中输入内容吗?

javascript - React.js Route - 重定向后保留上一页

html - Twitter 的 Bootstrap - 创建一个包含 2 列的表单