在多帧页面上只加载一次jQuery

时间:2011-06-30 18:09:03

标签: javascript jquery iframe

我的应用程序中的一个关键屏幕涉及一个HTML页面,其中有几个iframe执行各种功能。所有这些都需要访问jQuery。为了加快加载时间,减少HTTP流量(虽然我知道缓存可以帮助解决这个问题),但如果jQuery代码本身只加载一次就会很好。如果我的页面是这样的

<html>
   <head>
      <script src="jquery-1.5.js" type="text/javascript"></script>
   </head>
      <body>
         <iframe src="other.html"></iframe>
         <div id="foo"> ... stuff here ... </div>
      </body>
</html>

然后在other内我可以引用parent.$('#foo'),但这将引用父母的“foo”元素,而不是孩子的。有没有办法在子文档或其中的元素上使用父jQuery的“实例”?

3 个答案:

答案 0 :(得分:3)

确保每个IFRAME引用完全相同的jquery版本。它应该只加载一次并由浏览器缓存。 IFRAMES无法访问其父母的脚本。

您可能还想考虑使用CDN for Jquery(例如Google's CDN)来提高性能。

答案 1 :(得分:3)

你试过了吗?

var $ = window.parent.$;
$('#foo'); // parent's frame's #foo, is the same as "window.parent.$('#foo');"

var $ = window.parent.$;
$('#foo', document); // this frame's #foo because the current document is given as context

答案 2 :(得分:0)

我们解决了它:

var window.jQuery = window.$ = function( selector, context ) {
    return window.parent.jQuery(selector, context?context:window.document)
}