My friend Koop asked me over Twitter if there was an easy lazy-loading technique to load social media icons. Initially he wanted to load the icons over hover, but I talked him into doing it on a page load.

The problem with social media icons is that they are loaded from external sources, and are typically in iFrame format. These can delay a page load (in my experience) by as much as a minute.

While the page load doesn’t decrease with this technique, it allows the content to render, thus giving the visitor the impression that the site is loading rather fast.

Here’s some bare code you are free to expand upon. It’s basic, not necessarily secure, and not really optimized. However, if you’re a competent enough dev, you should be able to re-factor it to suit your use-case.

I placed the below code in a theme’s functions.php file. If you do decide to re-factor the code, please place a pastebin link so others can learn your technique as well.

<?php
//Ajax actions for lazy load
add_action( 'wp_ajax_nopriv_koop_lazy_load', 'koop_ajax_lazy_load' );
add_action( 'wp_ajax_koop_lazy_load', 'koop_ajax_lazy_load' );
function koop_ajax_lazy_load() {
	//Ajax response
	$post_id = intval( $_POST[ 'pid' ] );
	$permalink = get_permalink( $post_id );
	ob_start();
	?>
    <a href="https://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
    <?php
	$twitter = ob_get_clean();
	die( $twitter );
} //end koop_ajax_lazy_load

//Add the DIV to the content
add_filter( 'the_content', 'koop_the_content' );
function koop_the_content( $content ) {
	global $post;
	ob_start();
?>
	<div id='koop_lazy_load' rel='<?php echo absint( $post->ID ); ?>'>
    <input type='hidden' value='<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>' name='koop_ajax_url' id='koop_ajax_url' />
    </div>
<?php
	$return = $content . ob_get_clean();
	return $return;
} //end koop_the_content
add_action( 'wp_print_scripts', 'koop_print_scripts' );
//Load jQuery
function koop_print_scripts() {
	wp_enqueue_script( 'jquery' );
}
//Load our lazy loader script
add_action( 'wp_footer', 'koop_head', 100 );
function koop_head() {
	?>
    <script type="text/javascript">
    	jQuery( document ).ready( function( $ ) {
			var post_id = $( '#koop_lazy_load' ).attr( 'rel' );
			var koop_ajax_url = $( '#koop_ajax_url' ).val();
			//Do ajax
		$.post( koop_ajax_url, { action: 'koop_lazy_load', pid: post_id },
			function( response ){
				$( "#koop_lazy_load" ).html( response );
			} //end ajax response
		 ); //end ajax
		} );
    </script>
    
    <?php
} //end koop_head
?>

The code creates an empty container DIV below the post content. jQuery captures the post ID, sends an Ajax request, and the response contains the HTML for all the social media icons necessary. A sample Twitter button is included in the code.

Comments are closed.