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)

3 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
  2. Recharge Any Bangladeshi Mobile Balance from anywhere in the world from this site



    http://www.bdtopup4u.com

    Our Price Plan:

    01.30 pound = 100* Taka

    02.30 pound = 200* Taka

    03.30 pound = 300* Taka

    05.00 pound = 550* Taka

    06.00 pound = 660* Taka

    10.00 pound = 1100* Taka



    its simple and reliable



    *Price rate can be changed at any time.

    ReplyDelete

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