Reputation: 121
I am trying to develop an interactive widget that utilizes jQuery within an iframe, but relies on the jQuery object that already exists in the parent document rather than making an additional server request for its own jQuery instance. This is significant because the widget will be loaded into the parent document several times on a page - therefore requiring an http request each time it appears on the page is not desired. Instead, I would like to pass the parent's jQuery object instance (I am certain it will be available in the parent document) to be used within the iframe.
With the understanding that this is a "friendly" iframe (i.e. it is permitted to openly communicate with the parent document), I assumed it would be as simple as:
window.jQuery = window.parent.jQuery;
While this seems to provide the jQuery namespace to become available within the iframe (and logging this namespace shows the expected jQuery function string), it does not seem to be able to reference elements within the iframe. For example:
window.jQuery = window.parent.jQuery;
console.log(jQuery); // logs: function (e,t){return new w.fn.init(e,t,r)}
console.log(jQuery('#elem-in-iframe')); // logs: []
Therefore it seems like the jQuery object being passed into the iframe from the parent document is still limited by the scope of the parent.
Ultimately, I have had to settle for creating an independent instance of jQuery within each iframe that loads on the page - so instead of loading the jQuery library once on initial page load, it is loaded on initial page load as well as each time the widget is injected into the parent document. While this does not inhibit the parent window from loading, as the iframe loads independently, it is not the desired result. I would like to explore how it may be possible to inherit and use jQuery from the parent within the iframe.
Upvotes: 2
Views: 1283
Reputation: 64707
I think you are wrong in your assumption
therefore requiring an http request each time it appears on the page is not desired
jQuery will be cached by the browser as long as it is getting it from the same URL. It is basically a free request.
Now, the reason you can't "share" the jQuery object as you want, is that selector's have a context.
A DOM Element, Document, or jQuery to use as context
The default is document
(I believe), and as you are accessing the parents object, it's default is the already set document. You should be able to do:
window.jQuery = window.parent.jQuery;
jQuery('#elem-in-iframe', document)
In the iframe to pass in the iframes window as the context, and then it should theoretically work.
You may even be able to do this in the iframe:
window.jQuery = window.parent.jQuery;
$ = jQuery(document);
and then you can just do
$('#elem-in-iframe')
Upvotes: 2