July 26, 2011

Dont Reload jQuery on your Iframes

So, you may have some pages (in the same domain) that always are going to be loaded as iframes. But if you have jQuery loaded in the parent document and you want to use it INSIDE the iframe (a script tag inside) you just have to do this:

var $ = function(a,b){
 b = b || document;
 return parent.jQuery.apply(this,[a,b])
};

But that is only if you are not going to use document.ready or any of its shortcuts. If you want to use any of those there is a workaround (Note: The iframe needs to have an id)

var $ = function(a,b){
 var that = this;
 b = b || document;
 function ready(a){
   parent.jQuery("#"+window.frameElement.id).load(function(){a.call(that)})
 } 
 if(typeof a == "function"){
  ready(a)  
 } else {
  var r = parent.jQuery.apply(this,[a,b]);
  r.ready = ready;
  return r 
 }
};

So now you can write jQuery like it was loaded naturally inside the iframe (using the dollar sign)

2 comments:

  1. Awesome code, only problem I'm having is when trying to use it on methods like $.extend, $.trim, $.param.

    ReplyDelete
    Replies
    1. Also, not sure if it's relevant but I'm using this method between two iframes, not from parent. This iframe will never be called unless another iframe from the same domain is loaded first.

      for(var x = 0; x < window.parent.frames.length; x++){
      try{
      if(window.parent.frames[x].location.href){
      var $ = function(a,b){
      b = b || document;
      return window.parent.frames[x].jQuery.apply(this, [a,b])
      };
      break;
      }
      }catch(e){}
      }

      Delete

You can use [CODE][/CODE] to post Javascript code.
You can start a sentence with ">" to make a quotation.