Defer Parsing of JavaScript in WordPress for Faster Initial Loading

This is a simple tutorial for beginners in WordPress on how you can defer parsing of JavaScript to improve the page loading performance of your blog. This also improves your Google Page Speed score which is a search engine ranking factor used by Google.

Initially, JavaScript interferes with the other important page elements loaded such as your main text content that the visitor wants to see first. If JavaScript elements are taking so long to load, it will block the initial rendering of your content and other important parts forcing your visitor to close your page or even press the browser back button. Therefore this aspect can affect user experience.

Basic Tools Needed: Firebug and Google Page Speed

First, it is recommended you use latest version of Firefox web browser; then download and install Firebug.

Once you get that working, you need to download and install Google Page Speed add-on for Firebug. Make sure to select the “Page Speed Extension for Firefox”.

Restart your Firefox browser and go to your WordPress blog. Perform the following steps below:

1.) Select any of your WordPress post and load it completely in the browser.
2.) In your Firefox browser, go to “Web Developer” – “Firebug” – Go to “Page Speed” tab and click “Analyze Performance”. Google Page Speed will then analyze the page.
3.) You should see an issue reported as “Defer Parsing of JavaScript”. Expand that one; it should look similar to this:

It shows that there around 863Kb of JavaScript parsed during initial page loading. This interferes with the normal page loading of your more important blog sections. Examples of JavaScript as reported in the Page Speed report are Facebook like box, Facebook like button java script, etc.

You need to use a combination of Firebug and Google Page Speed to assess the improvement after you have deferred the parsing of JavaScript. The goal is to lower down the kilobytes of java script loaded to a possible minimum.

Enable jQuery in WordPress

In this tutorial, you will be using jQuery library to defer the parsing of JavaScript in your WordPress blog. The good thing is that jQuery was included with the recently released versions of WordPress.
This will be used by your themes and your plug-ins. The path to the jQuery library in WordPress is (as of WordPress 3.3): /wp-includes/js/jquery/jquery.js?ver=1.7.1

To check if your WordPress blog already loaded jQuery, follow the steps below:

1.) Go to any of your WordPress post and load them completely in the browser.
2.) View the page source code of that post.
3.) If your themes already loaded jQuery library, you should see the path to the library: /js/jquery/jquery.js?ver=1.7.1

In most cases, it will show in the head section if you are logged-in as administrator or it will show somewhere in the footer if you are not logged in. Also it will be loaded by some of the plug-ins and currently used themes.

If you do not see the path, you need to enable jQuery by following the steps below:

1.) Login as administrator to your WordPress blog.
2.) Go to header.php file of your theme and add this PHP source code just before </head>

<?php wp_enqueue_script('jquery'); ?>

3.) Save the changes.
4.) If you are using any cache solutions such as WP Super Cache or Quick cache, you need to clear the cache and load the page again so that your changes will be incorporated.
5.) Load any of your WordPress post again and view the page source; you should now be able to see the path to your jQuery library in wp-includes.

Note: A more recommended method of enabling jQuery in WordPress is to use Google libraries plugin.

Sample Application: Defer Parsing of Facebook Likebox and Like Button

Let’s have an actual illustration on how to actually defer parsing of JavaScript using jQuery in WordPress. One of the commonly used widgets in the WordPress blog is Facebook like box and like button. These widgets depend on the JavaScript hosted on Facebook. It actually slows down the loading of the page because these elements can be heavy at times.

It is recommended that you backup affected template files in your WordPress blog before doing any changes. Follow the steps below:

1.) Get the actual code of Facebook Like box widget and Like Button used by your WordPress blog, for example:

Facebook Like Box example code:

<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<fb:like-box href="http://www.facebook.com/pages/php-developerorg/148874655176387/" width="278" show_faces="true" stream="false" header="true"></fb:like-box>

Facebook Like Button example code:

<iframe src="http://www.facebook.com/plugins/like.php?href=<?php urlencode(the_permalink());?>&amp;layout=standard&amp;show_faces=false&amp;width=385&amp;action=recommend&amp;font=verdana&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:385px; height:35px;" allowTransparency="true"></iframe>

2.) Define a new JavaScript global object that can be used for jQuery exclusively for your deferred applications. This will avoid any conflicts with the use jQuery for your plug-ins and themes. Also since this deferred element would now be placed outside the WordPress loop, you need define a variable for retrieving the permalink URLs.


<?php
//Retrieve post ID for retrieving permalink URL
global $wp_query;
$thePostID = $wp_query->post->ID;
?>
<script type="text/javascript">
$myjQueryvariable = jQuery.noConflict();
</script>

Place the code after:

<?php wp_footer(); ?>

In your templates.

3.) Define the jQuery syntax for deferring the Facebook like box and button. This is the complete working jQuery code:

<script type="text/javascript">

$myjQueryvariable(document).ready(function() {
$myjQueryvariable(‘#deferfacebooklikebox’).append(‘<fb:like-box href=”http://www.facebook.com/pages/php-developerorg/148874655176387/” width=”278″ show_faces=”true” stream=”false” header=”true”></fb:like-box>’);
$myjQueryvariable(‘#deferfacebooklikebutton’).append(‘<iframe src=”http://www.facebook.com/plugins/like.php?href=<?php echo urlencode(get_permalink($thePostID));?>&amp;layout=standard&amp;show_faces=false&amp;width=385&amp;action=recommend&amp;font=verdana&amp;colorscheme=light&amp;height=35″ scrolling=”no” frameborder=”0″ style=”border:none; overflow:hidden; width:385px; height:35px;” allowTransparency=”true”></iframe>’);
jQuery.getScript(‘http://connect.facebook.net/en_US/all.js#xfbml=1’, function() {FB.init({status: true, cookie: true, xfbml:true});});});

</script>

Place above jQuery code just after:


<?php
//Retrieve post ID for retrieving permalink URL
global $wp_query;
$thePostID = $wp_query->post->ID;
?>
<script type="text/javascript">
$myjQueryvariable = jQuery.noConflict();
</script>

Screenshot of the above code implemented:

4.) Replace the old Facebook like box code and button with a div id referencing to your jQuery code. For example:

<div id="fb-root"></div> <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<fb:like-box href="http://www.facebook.com/pages/php-developerorg/148874655176387/" width="278" show_faces="true" stream="false" header="true"></fb:like-box>

Replace the above code simply with:

<div id="fb-root"></div>
<div id="deferfacebooklikebox"></div>

deferfacebooklikebox” is the div id used by your jQuery code to identify with the Facebook like box.

Then for the Facebook like button, replace:

<iframe src="http://www.facebook.com/plugins/like.php?href=<?php urlencode(the_permalink());?>&amp;layout=standard&amp;show_faces=false&amp;width=385&amp;action=recommend&amp;font=verdana&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:385px; height:35px;" allowTransparency="true"></iframe>

With:

<div id="deferfacebooklikebutton"></div>

Where “deferfacebooklikebutton” is the div id used by your jQuery code to identify with the Facebook like button.

Screenshot of actual code implementation:

5.) Save all changes then clear the cache of your WordPress blog (if you are using any cache solutions).

6.) Reload any of your WordPress posts and run Google Page Speed again. Take note how much improvement was made. For example, below is the screenshot after implementation:

Based on the results, the amount of JavaScript during the initial page load was reduced from 862.3kB to 281.7kB after deferring Facebook like box and like button. This could be reduced further if other JavaScript elements are deferred also.

However, you cannot defer all JavaScript particularly the Google Ad Sense scripts and other related scripts because doing so is against the terms and conditions of Google Ad Sense.

Adding another Facebook related widgets to defer

In the above code, you can further add another Facebook related scripts which are JavaScript-heavy for example the Facebook comment box. To do this, simply add a new line and assign a new id in your existing jQuery code above, e.g.:

$myjQueryvariable('#deferfacebookcommentbox').append('<fb:comments colorscheme="dark" num_posts="5" href="<?php echo get_permalink($thePostID); ?>"></fb:comments>');

And then replace the original Facebook comment box code in your template with the div tag referenced to an assigned id used in the jQuery code (e.g. deferfacebookcommentbox):

<div id=" deferfacebookcommentbox"></div>

16 thoughts on “Defer Parsing of JavaScript in WordPress for Faster Initial Loading

  1. MetaTrader MQL Services - April 14, 2012 at 2:07 am

    You for sure know your stuff!

    Thanks for the instructions on deferring java-script.
    I found it useful and will implement your instructions.

    Keep it up.

  2. jeet - June 8, 2012 at 2:08 pm

    nice…really good piece of information..i want to implement those code now.

  3. Michael B - June 9, 2012 at 7:04 pm

    I’d like to implement this, but maybe I’m missing something. The plugin code (editor screen) for the FB Like Box plugin I’m using is way more than the few lines of code you have above. If I view the source of the homepage then yes, it appears closer to that. But as it stands now, all I have is the screen where I can edit the plugin itself, so where is the code I would actually be replacing in step 4? Thanks.

    • Codex Meridian - June 28, 2012 at 6:55 pm

      Hi Michael,
      What you are doing is bit complicated. I suggest you contact the plugin author and ask for instructions on how to integrate the code.
      The above tutorial assumes you are not integrating the code to any plugin. Good luck.

  4. Gautam Doddamani - June 28, 2012 at 2:35 pm

    NOT WORKING

    this code doesn’t work… i hav tried it. it says Uncaught SyntaxError: Unexpected token ILLEGAL when i checked through inspector on chrome. please UPDATE YOUR CODE!!!

      • Gautam Doddamani - June 29, 2012 at 12:54 am

        yes i am perfectly sure i triple checked the code just to see if there was an invisible character…the error is also appearing in firefox firebug…the line it is showing the error, is below this code

        $myjQueryvariable(‘#deferfacebooklikebox’).append(‘’);

        i dont know what illegal character is there…i also checked it in jslint.com but it is showing the same error…can u please fix the code!!

  5. Turismo in - July 13, 2012 at 8:17 pm

    Yes, you’re the only one has this script, can you fix it? Please..

    • Codex Meridian - July 14, 2012 at 3:33 pm

      I cannot anymore edit the post, but here is what I’ve found:

      1.) I implement the above code in another website and it throws “illegal” error in console using Firebug. The Likebox is not loading. So something is wrong with the code posted above.

      2.) I found out that its due to the presence of apostrophe in the code above. The code is basically correct but it changes single quotes to apostrophe when the post is published. Do not why but try pasting the code in gedit or notepad and it will change:

      '

      TO this:

      �

      That one basically throws the illegal error in console. Then the jQuery code will not properly execute. I change them to single quotes and the error is gone.

      THE FIX:

      Note: This fix will only illustrate the Facebook likebox code. The rest of the widgets will follow the sample implementation.

      1.) Get the latest Facebook likebox widget code here:

      http://developers.facebook.com/docs/reference/plugins/like-box/

      2.) Use the HTML5 code, for example this is the resulting code for the Like box:

      <div class="fb-like-box" data-href="http://www.facebook.com/pages/php-developerorg/148874655176387" data-width="290" data-show-faces="true" data-stream="false" data-header="false"></div>

      Simply ignore the SDK Async JavaScript you will not be using that. You will only be using the Likebox code provided.

      3.) Use the Likebox code in the jQuery script tag, for example:


      <script type="text/javascript">
      $myjQueryvariable(document).ready(function() {
      $myjQueryvariable('#deferfacebooklikebox').append('<div class="fb-like-box" data-href="http://www.facebook.com/pages/php-developerorg/148874655176387" data-width="290" data-show-faces="true" data-stream="false" data-header="false"></div>');
      jQuery.getScript('http://connect.facebook.net/en_US/all.js#xfbml=1', function() {FB.init({status: true, cookie: true, xfbml:true});});});

      4.) Therefore the final code in your footer.php (right after:

      <?php wp_footer(); ?>
      ) will be:


      <script type="text/javascript">
      $myjQueryvariable = jQuery.noConflict();
      </script>


      <script type="text/javascript">
      $myjQueryvariable(document).ready(function() {
      $myjQueryvariable('#deferfacebooklikebox').append('<div class="fb-like-box" data-href="http://www.facebook.com/pages/php-developerorg/148874655176387" data-width="290" data-show-faces="true" data-stream="false" data-header="false"></div>');
      jQuery.getScript('http://connect.facebook.net/en_US/all.js#xfbml=1', function() {FB.init({status: true, cookie: true, xfbml:true});});});
      </script>

      5.) Then you can embed the Like box within your WordPress template (using sidebar widgets or any method) with this code:

      <div id="fb-root"></div>
      <div id="deferfacebooklikebox"></div>

      The code now works, no error in Firebug JS console and the Like box now loads in deferred mode.

      IMPORTANT: If you find this solution too complex or still not working for you. I recommend to implement the new asynchronous JavaScript loading instead of deferred solution, it is similarly faster and less complex. The good news is that all social networking sites like Facebook Twitter and Google + now defaults to asynchronous mode when loading their JS library. All you need is to update your old Facebook, Google + and Twitter code to use asynchronous mode. You do not need to use the deferred mode.

      I just wrote a tutorial about this and will be published soon here in WPWebhost. Thanks for everyone for reporting this error. Cheers.

      • Gautam Doddamani - July 25, 2012 at 3:02 pm

        thanks for making the code work u r a life saver 😀 i would strongly recommended you to use the syntaxhighlighter plugin…dat way your code will be shown “as is”…ppl get very annoyed when a given code doesn’t work!

        thanx again 🙂

        • Codex Meridian - July 25, 2012 at 5:50 pm

          Thanks for the tip Gautam! I’m glad to know it now works. I will check on that plugin to see if its installed in wpwebhost so writers can use it. Cheers 🙂

  6. Fabricio - August 19, 2012 at 8:42 pm

    awesome! your script works perfectly! thank you very much!

  7. walif - August 27, 2012 at 3:10 am

    This is so amazing post and i enjoyed much.I have spent more than 3 hours in your blog site.It is really helpful.

  8. Ratanak - December 4, 2012 at 4:53 pm

    Hi, friend

    I tried to apply your script many times but I don’t know why it does not work. Even the like button/box/and comment, it does not show.

    I am so wondering whether your code does work.

    Thank you so much, please help

  9. Phil - March 1, 2013 at 6:08 am

    Hi Codex Meridian, like most people I am finding that through gtmetrix I am getting this js issue, I am using wp 3.5.1, add link to facebook 1.176 as well as wp-rss agregator 2.2.3 with a few others including the wp to twitter 2.5.9

    I am concerned after finding out that google now uses page speed on rank, I know my site is not ranked highly yet but reducing this issue now will save me headaches in the future. Your post seems to be the most comprehensive and also the one that makes the most sense but I am unsure of where to put the code, which files etc. I have filezilla so am not encumbered by one.coms daft file management and any help you can give would be greatly appreciated.

Share your thoughts with the community