4

我有一个 web 应用程序,它有几个 iframe,它们都需要导入相同的 javascript 库(例如 jquery)。

有没有办法只加载一次并以某种方式在所有 iframe 之间共享该数据?我宁愿不要让我的页面加载缓慢,因为它会为每个 iframe 加载一次相同的 JS 文件。

谢谢!

编辑:人们说你不能从 iframe 共享数据,但是如果 js 导入都在一个命名空间中,比如 NAMESPACE,然后 iframe 会执行类似 NAMESPACE = parent.NAMESPACE 的操作

4

3 回答 3

3

假设您src使用相同的 URI,并且您有健全的缓存控制标头,那么 JS 将被缓存并且不会为每个帧重新下载。

也就是说,如果你真的想要,你可以将它加载到顶部框架中,然后通过parent对象访问所有内容。

例如:http ://dorward.me.uk/tmp/frames/top.html

于 2012-07-05T16:23:04.170 回答
3

如果所有框架都加载相同的 js 文件,现代浏览器(chrome、firefox、IE)应该简单地从缓存中加载相同的文件......所以你不必一遍又一遍地重新加载相同的文件。如果您的页面加载时间很长,请考虑缩小您的 javascript(通过使用另一个程序使您的 js 文件更小)...这可以大大减少加载时间。

于 2012-07-05T16:25:02.477 回答
0

Certain environments generate iframe urls you can't control. In CRM Dynamics, for example, I had the same thought. I have common web resources, but when included as a dependency of another resource the library ended up downloading again. I wanted the library to cross the wire once but that didn't happen.

Even if you manage getting your library to load once as I eventually did you'll have issues sharing it across iframes. The host objects and types (e.g. classes) are unique to the iframe.

function isHTMLDocument(el){ //impure
  return el instanceof HTMLDocument;
}

function dropdown(values){ //impure
   const el = document.createElement("select");
   ...
   return el;
}

If you call methods against foreign iframes hopefully you can see the problem. HTMLDocument in the context where your library loads will not be the same as HTMLDocument in a foreign iframe. While isHTMLDocument will work on document in the local environment it won't work in the foreign one.

Same with document and many libraries bake document into functions to avoid requiring you to pass it in again and again. Unfortunately, due to each environment being its own sandbox, host-environment tainted functions are effectively broken.

Only pure functions would work when used in a foreign context like an iframe document.

function is(el, type){ //pure
  return el instanceof type;
}

function dropdown(document, values){ //pure
   const el = document.createElement("select");
   ...
   return el;
}
于 2021-07-02T19:47:49.110 回答