gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:39:59 25 4
gpt4 key购买 nike

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

每当我想在网站上创建一个弹出窗口时,我都会使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com