Speed up website by dynamic social section load

Speed up website by dynamic social section load
Speed up website by dynamic social section load

Speed up your website or webpage by dynamic social section load. Social section includes Facebook Page Plugin, Google+ page Badge etc., third party content which takes time to load from remotely.

When we add Page Plugin, Google+ page Badge or other social content in website, every section make 3-4 call to remote server for get related content. It will block page rendering and slow down page load.

Here is simple process for load social section dynamically when social div comes in viewport.

Steps for dynamic social section load

  1. Add div with id for social content
  2. Get social section(Page Plugin,Google+ Badge) code
  3. Add javascript function for check div show in viewport
  4. Add scroll event for load social section

1. Add div with id for social content

<div id="fbBox"><div>

2. Get social section(Page Plugin,Google+ Badge) code

Get social section code from social sites e.g., Page Plugin, Google+ Badge.

3. Add javascript function for check div show in viewport

Below function used for check if element is visible after scrolling. Found it from stackoverflow.

function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();

var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();

return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

4. Add scroll event for load social section

Process check social section div comes in viewport, if it comes in viewport it will add social code in given div based on id and set flag for stop process repetition.

$(function(){
    //flag to execute process only one time
    var socSecNotLoad = true;

    $(window).on('scroll', function(){
        if(socSecNotLoad && isScrolledIntoView( $('#fbBox') )){
            $('#fbBox').html('<div id="fb-root"></div>'
                +'<script>(function(d, s, id) {'
                .....
                +'</div>');

            socSecNotLoad = false;
        }
    });
});