2

I am embedding an iframe in a webpage and I want to inject jquery in this frame.

I tried something like:

frame.contentWindow.$ = window.$

While this works, the iframe's $ is still running in the parent's scope as opposed to its own independent copy.

Is there a way to inject an independent jquery object into the iframe without injecting a <script src="/path/to/jquery.js"></script> in the frame?

UPDATE

Solved it. The jquery.js conveniently defines jQuery for a scope by accepting the window object in an anonymous function:

function(windowObject){ .... define jquery }(window)

So all I had to do was to name this function, E.g. jQuerify and call it once for the parent window object and then for the child window object.

jQuerify = function(windowObject){ .... define jquery }
jQuerify(window)
jQuerify(iframe.contentWindow)
Coffee Bite
  • 4,956
  • 5
  • 33
  • 38
  • 1
    Why not just inject the script tag? It will load from cache. You need it to run fresh from scratch as it loads so that it will re-initialize itself in the new context. – jfriend00 May 02 '12 at 02:06
  • you could also have a look into http://api.jquery.com/jQuery.sub/. Be aware that `.sub()` is a plugin since 1.7.0 – jAndy May 02 '12 at 02:17
  • @jfriend00 I serve my jquery with a lot of other libraries. That file is super heavy. I don't want the iframe to process all that javascript. – Coffee Bite May 02 '12 at 02:17
  • @jAndy The sub documentation says that sub methods still call the original jquery object. – Coffee Bite May 02 '12 at 02:19
  • 1
    I've got news for you. If you want a new instance of jQuery, you have to load a new instance of jQuery. If you only want jQuery and not everything else the parent frame is using, then put just what you need in the iframe. There is no secret answer here. Put the scripts you need in the iframe. – jfriend00 May 02 '12 at 02:21
  • Thanks @jfriend00. Appreciate the news. – Coffee Bite May 04 '12 at 07:13

2 Answers2

1

Solved it. The jquery.js conveniently defines jQuery for a scope by accepting the window object in an anonymous function:

function(windowObject){ .... define jquery }(window) So all I had to do was to name this function, E.g. jQuerify and call it once for the parent window object and then for the child window object.

jQuerify = function(windowObject){ .... define jquery }
jQuerify(window)
jQuerify(iframe.contentWindow)
Coffee Bite
  • 4,956
  • 5
  • 33
  • 38
0

You can try cloning the jQuery object:

See this answer or this one on how to implement a .clone function, then call this:

iframe.contentWindow.$ = window.$.clone();

or

iframe.contentWindow.$ = window.$.bind({});

... depending on how you choose to clone the function.

Community
  • 1
  • 1
Jeff Meatball Yang
  • 37,839
  • 27
  • 91
  • 125