开发者

Load jQuery only once on many-framed page

开发者 https://www.devze.com 2023-03-17 00:20 出处:网络
A key screen in my application involves a HTML page with several iframes performing various functions. All of these will need access to jQuery. In开发者_如何学运维 the interest of speeding up loading

A key screen in my application involves a HTML page with several iframes performing various functions. All of these will need access to jQuery. In开发者_如何学运维 the interest of speeding up loading time, and reducing HTTP traffic (though I know caching could help with this), it would be good if the jQuery code itself were loaded only once. If my page is like so

<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>

Then inside other I can refer to parent.$('#foo') but that will refer to the parent's "foo" element, not the child's. Is there a way to use the parent's "instance" of jQuery on the child document or elements in it?


Have you tried:

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

and:

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


Make sure each IFRAME references the exact same version of jquery. It should only get loaded once and be cached by the browser. IFRAMES don't have access to scripts of their parents.

You might also want to consider using a CDN for Jquery (such as Google's CDN) to improve performance.


We solved it with:

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

精彩评论

暂无评论...
验证码 换一张
取 消