Skip to main content

Defer Parsing of JavaScript in WordPress for Faster Initial Loading

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>阅读更多内容

该邮件由 QQ邮件列表 推送。
如果您不想继续收到该邮件,可点此 退订

Comments

Popular posts from this blog

Over A Year After Android Launch, ShopSavvy Finally Comes To The iPhone

ShopSavvy was one of the best early Android applications. It launched in October of last year after winning one of the initial Android Developer Challenge top prizes (when it was still known as GoCart). But despite the success it has seen on Android, one question remained: When would it be available for the iPhone. Today, it finally is. Developed by the guys at Big In Japan , ShopSavvy is an app that allows you to use your device as a portable barcode scanner. You point your phone's camera at any barcode and it will read it, do a product look up, and give you information about the product, as well as where you can find it online or at nearby stores and for how much. Obviously, something like this is a window shopper's dream. ShopSavvy was one of the best early Android applications. It launched in October of last year after winning one of the initial Android Developer Challenge top prizes (when it was still known as GoCart). But despite the success it has seen on Android, o

How to find ideas to post new article in your blog

How to find ideas to post new article in your blog    阅读原文»   It is true that sometimes being a blogger may face situations where I would personally like to call it your brain juices got dried up as you have pretty much ran out of topic to blog and you are in crisis as your readers are anxiously waiting for your new posts but you are unable to give in. That’s when you will probably come with excuses like I just posted last week although that post was more directly towards the newbies who stop themselves from making money but it’s still pretty much the same even though you consider yourself not a newbie. The fact is that ideas are everywhere and I mean everywhere if you know where to find it and know how to leverage it. You may be surprised that sometimes these ideas are just right in front of you but you are not observant enough to convert these ideas and turn it into your blog post. Today I will share some tips on where to get these ideas and most of it is part of your dai

Lindsay Lohan Breakup Confirmed by Lohan, Locksmith, Police [Gossip Roundup]

Farewell, last season's Suri Cruise fashions. Goodbye, Amy Winehouse's bathing suit. Adieu, humanoid version of Lauren Conrad. And so long, LiLo and SamRon's fairytale romance. Lindsay Lohan confirmed her split with Samantha Ronson and insisted the decision was part of a very healthy and mature effort to " focus on myself ." Upon hearing this, Ronson changed her locks and discussed a restraining order with police, so confident was she in Lohan's ability to turn productively inward. Lohan promptly had a run-in with the police . Who would have imagined such a messy breakup for this model relationship? Courtney Love's lawyer, on her client's drug-fueled plunge into broke-ness: ""Courtney noticed the money was gone when there wasn't any left." Deadpan gallows humor: the only possible response to having Courtney Love as a client. (Besides asking for a hefty retainer.) [ P6 ] Before Lauren Conrad's contract expired in March, MTV