Friday, October 15th, 2010 | Adventures, jQuery, Web Dev, WordPress

Make iframes load after page content (with jQuery)

In my work I create a lot of WordPress sites for my clients, and often times we’ll put the share links and social proof in the footer of each post. Some time ago, facebook introduced the like button for public use with iframes, which makes it very easy to incorporate just about anywhere, the only problem is that the iframes slow down the loading of the site, especially effecting things like javascript functionality, sometimes, it hangs on waiting for facebook, so instead of my content loading, I’m waiting on facebook:

I’ve been trying to come up with a solution for this. So I asked my friend Brian Morykon his thoughts. He suggested using spans instead of iframes, then when the dom was ready to replace the spans with iframes throughout, that way it would load after everything else. I tried it, and it worked. The only thing that is a little different here is that I am only using the src attribute from the spans, the other parameters I’m filling in on .replaceWith()

Facebook Like button (using span instead of iframe)

<div class="facebooklike">
 <span class="facelike" src="http://www.facebook.com/plugins/like.php?href=<?php the_permalink(); ?>&amp;layout=button_count&amp;show_faces=false&amp;width=60px&amp;action=like&amp;colorscheme=light&amp;height=21"></span>
</div>

jQuery function to find and replace spans with class ‘facelike’:

jQuery("span.facelike").each(function() {
 var url = jQuery(this).attr("src");
 jQuery(this).replaceWith('<iframe src=' + url + ' scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:60pxpx; height:21px;" allowTransparency="true" />');
 });

Note:

  1. The jQuery is replacing the span with class ‘facelike’ with an iframe, with the attribute the same as the span. the other parameters (frameborder, style, scrolling) get passed from the jquery and not pulled out of each span (it’s much easier this way, plus you can change them all at once if you need to adjust).
  2. This doesn’t have anything to do with jQuery, more with WordPress, but I’m using the_permalink() to pass the url to like, so you have to run this inside the loop.

No Comments yet

Leave a Comment