First, check out my fiddle fiddle
jsFiddle is nice, but sometimes it runs a bit slow, so I made this simple pure JS fiddle (can be ran locally)
Working great so far, but I want to be able to use jQuery in my fiddle. Type alert(typeof $); in the bottom left box and press “Run” to see what I mean (says undefined).
So how do I pass jQuery off to the iframe and give it the correct context? I suspect I could set doc.contentWindow.$=$ or something like that, but I still need to give the correct context so it knows where to find the elements. How would I do that?
iframe.contentWindow.$ = $.proxy($,iframe.contentWindow);
That didn’t work either. Gives me access to jQuery, but the context is still wrong.
iframe.contentWindow.$ = function(s){return $(s,doc);};
That sort of works… but it’s a bit of a hack.
Why not do as jsfiddle itself does? It simply includes a script tag for jQuery (or whatever framework you asked for) in the
headof theiframe.If you look in
headof the… uh “outer”iframe(the one jsfiddle created), you’ll see they just threw this in there:Same thing applies to the “on ready” and “on load” options, jsfiddle just wraps the appropriate call around your javascript before injecting it into the iframe.
Modifying your code a little, you can create a
scriptelement:and then append that element to the
head.