Improve Page Speed by Loading JavaScript Asynchronously

Because JavaScript can modify the DOM and affect how the page is rendered, browsers traditionally load and execute scripts synchronously. While a script is being downloaded and run, later code on the page is blocked. That blocking behavior is safe, but it also slows down rendering. If we can load some scripts without blocking the rest of the page, overall page speed improves.

In the example below, social-sharing code is loaded asynchronously in a WordPress theme so the page content can keep rendering without waiting for third-party social networks to respond.

What asynchronous JavaScript loading means

Asynchronous loading means the browser downloads and executes JavaScript without blocking the rest of the page. There are several ways to achieve that. The method shown here is one of the most common: inside a <script> tag, use JavaScript to create another script element dynamically and insert it into the document. That turns the remote script load into a non-blocking request.

The benefits of asynchronous loading

  • It improves page speed because the page no longer waits for a third-party server before continuing to render.
  • The site content becomes more independent. If the social network’s server is slow, the page content itself is not held up.
  • It helps reduce user waiting time, which can lower bounce rate and may indirectly help SEO.
  • If users stay on the site longer because it feels faster, they are also more likely to share the content.

Here is a simple three-step way to do it in a WordPress theme. You can adapt the code below for your own JavaScript files or third-party services.

Step 1: Create the JavaScript file

For example, put the following code into a file named share.js inside the theme’s js directory.

/* Load share-button JavaScript asynchronously */
 (function(w, d, s) {
 
   // Run after the page has loaded
   function go(){
  	   var js, fjs = d.getElementsByTagName(s)[0], load = function(url, id) {
  	   if (d.getElementById(id)) { return; }
    	  js = d.createElement(s); js.src = url; js.id = id;
    	  fjs.parentNode.insertBefore(js, fjs);
  	   };
   
       // Load social sharing scripts
  	   load('//connect.facebook.net/en_US/all.js#xfbml=1', 'fbjssdk');  // Facebook
  	   load('https://apis.google.com/js/plusone.js', 'gplus1js');       // Google+
  	   load('//platform.twitter.com/widgets.js', 'tweetjs');            // Twitter
  	   load('//platform.linkedin.com/in.js', 'lnkdjs');                 // LinkedIn
  	   load('//assets.pinterest.com/js/pinit.js', 'pinitjs');           // Pinterest
    }
 	if (w.addEventListener) {
        w.addEventListener("load", go, false); 
    }
  	else if (w.attachEvent) {
        w.attachEvent("onload",go); 
    }
}(window, document, 'script'));

If you have ever looked at the asynchronous tracking snippets used by Baidu Analytics or Google Analytics, this pattern will probably look familiar.

Step 2: Enqueue share.js in the theme

Add the following code to the theme’s functions.php file:

/* Add the script in functions.php */
function meks_load_scripts(){
 
  // Only load it on single-post pages. Use is_singular() for posts and pages,
  // or remove the condition entirely if it should load on archives too.
  if(is_single()){
    wp_enqueue_script( 'meks_async_share', trailingslashit(get_template_directory_uri()).'/js/share.js', array( 'jquery' ));
  }
}
 
add_action('wp_enqueue_scripts', 'meks_load_scripts');

Step 3: Add the HTML placeholder code in the theme template

Finally, insert the placeholder HTML into the relevant theme template, ideally inside the Loop. After the JavaScript finishes loading, the share buttons are rendered in the placeholder position.

<?php if( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php the_title(); ?>
<?php the_content(); ?>

<ul class="meks_share">
<!-- twitter -->
<li><a class="twitter-share-button" data-count="vertical" data-via="mekshq" data-url="<?php the_permalink() ?>"></a></li>

<!-- LinkedIn -->
<li><script type="IN/Share" data-counter="top" data-url="<?php the_permalink() ?>"></script></li>

<!-- Facebook like -->
<li><div class="fb-like" data-send="false" data-layout="box_count" data-width="50" data-show-faces="false" data-href="<?php the_permalink() ?>"></div></li>

<!-- g+ -->
<li><g:plusone size="tall" data-href="<?php the_permalink() ?>"></g:plusone></li>

<!-- Pinterest -->
<li><a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink() ?>&media=<?php echo wp_get_attachment_url( get_post_thumbnail_id() ); ?>&description=<?php echo urlencode(get_the_title()); ?>" class="pin-it-button" count-layout="vertical"><img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" /></a></li>
</ul>

<?php endwhile; ?>
<?php endif; ?>

There are also dedicated libraries for asynchronous JavaScript loading, such as ControlJS and HeadJS, if you want a more abstracted solution.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *