How to Defer Parsing of Javascript in WordPress

//How to Defer Parsing of Javascript in WordPress

How to Defer Parsing of Javascript in WordPress

There are many reasons why you want to defer parsing of Javascript in WordPress. One of the most obvious reasons is speed. Normally, Javascript is being place in the between <head> </head>. When we are loading a website, what it does is to load from top to bottom. Therefore, if you  have a lot of Javascript code or a long string of code there, it will take very long before the website’s content will appear, because it needs to wait until all Javascript codes are finished. In order to speed up the site, we can defer parsing of Javascript, so the website doesn’t have to wait for Javascript codes to finish. There are basically two ways to do that, beginner’s way and more advanced way.

Let’s begin with the advanced way: coding. Basically, all you need to do is to copy the following code into the function.php of your theme:


function defer_parsing_of_js ( $url ) {
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) ) return $url;
return "$url.' async onload='myinit()";
}
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );

Or

function defer_parsing_of_js ( $url ) {
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) ) return $url;
return "$url' defer ";
}
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );

and save it. However, before to place any code into your function.php, make sure you have ftp or cPanel login information ready, and backup  your function.php file first, because codes in function.php is very sensitive in a way, any missing codes will trigger errors on your site, and you won’t be able to login or reverse if you do not have ftp or cPanel login information ready.

Related:  Top 5 Ways to Speed Up WordPress

After that is done, you should notice increase in speed of your website. Always double check all features on your site, make sure they all works as they should.

Now, let’s move on to the easier one. The second way to defer parsing of Javascript in WordPress is by installing a plugin call “BJ Lazy Load”. You can simply go to plugins -> add New, and search for it. After found it, you can install and activate, and you are done. This plugin might have conflict with some of theme’s functionality, so double check after activated.

Of course, there is another plugin called “WP Defer Loading”, which is just like what it’s named, defer loading javscript, just what Google wants.

The above are three most common ways to defer Parsing of Javascript in WordPress, if you know a better way,  please let us know.

2014-03-31T17:17:12+00:00 By |Categories: WordPress Tutorial for Beginners|Tags: , |

About the Author:

Founder of Siteber: a full-stack web developer with more than 8 years working experience in WordPress, SEO, and internet marketing.

49 Comments

  1. jb August 21, 2014 at 7:09 pm - Reply

    I’ve add your code to my themes functions.php but nothing changed. Stil F in GTMetrix.

    • Feng Liu August 22, 2014 at 12:34 pm - Reply

      This can due to many factors, Do be aware that some plugins or thumbnail images might not function well if Javascript be placed before the
      – Try lazy loader plugin, see if works. (it has more options)
      – also check if you have cache plugin install and activated, clear cache and check again.
      etc.

  2. Ben August 29, 2014 at 2:34 pm - Reply

    Thanks for the excellent review of this subject! I took a look at the Lazy Load plugin you mentioned, but its WP page only talks about handling images, not deferring the parsing of JavaScript. Am I misunderstanding what the plugin does?

    Thanks,
    Ben

    • Feng Liu August 29, 2014 at 2:40 pm - Reply

      The lazy load plugin is created to defer parsing of javascript code; after you have installed and activated, you can go to Setting -> BJ Lazy Load to set it up. One thing to note is that you don’t want to defer every javascript in WordPress, because some of them might stop working.

  3. Juuth October 6, 2014 at 4:09 pm - Reply

    Hey Feng Liu, thanks a lot for this!

    I pasted it, got some errors but now it works. Here’s what worked for me:

    From your code i removed the opening and closing php tags and replaced the double quotation marks with single ones. So this is what i put in my (child) theme’s functions.php:

    function defer_parsing_of_js ( $url ) {
    if ( FALSE === strpos( $url, ‘.js’ ) ) return $url;
    if ( strpos( $url, ‘jquery.js’ ) ) return $url;
    return ‘$url’ async onload=’myinit()’;
    }
    add_filter( ‘clean_url’, ‘defer_parsing_of_js’, 11, 1 );

    Thanks again, your post got me on the way to a much faster website!

    Cheers, Judith

    • Feng Liu October 6, 2014 at 6:10 pm - Reply

      u r welcome

    • Jean October 10, 2014 at 11:40 am - Reply

      Hello Juuth & Feng Liu

      I am encountering the same problem, i have
      391.1KiB of JavaScript is parsed during initial page load. could you please give me the exact code i need to use and in which php file ( i run a wordpress site) to Defer parsing JavaScript to reduce blocking of page rendering.

      Many Thanks
      Jean

    • Luke Beck January 27, 2015 at 7:26 am - Reply

      I tried this code (with & without the tags):

      function defer_parsing_of_js ( $url ) {
      if ( FALSE === strpos( $url, ‘.js’ ) ) return $url;
      if ( strpos( $url, ‘jquery.js’ ) ) return $url;
      return ‘$url’ async onload=’myinit()’;
      }
      add_filter( ‘clean_url’, ‘defer_parsing_of_js’, 11, 1 );

      But I am getting a PHP syntax error, unexpected T_VARIABLE…on the ‘return’ line (but experience tells me, its actually the line before?!) I suspect its to do with the ‘jquery.js’ ?

      Suggestions please? 🙂

  4. Sanjay Maharjan February 2, 2015 at 10:02 am - Reply

    WP Defer Loading didn’t worked for me. However, BJ Lazy Load helped to increase few scores in GTMetrix. Despite using the plugin, the recommendation ‘Defer parsing of JavaScript’ is still there. I can’t figure it out.

  5. Alejandro February 5, 2015 at 4:28 pm - Reply

    Change this sentence:

    return “$url’ async onload=’myinit()”;

    for

    return $url.’ async onload=”myinit()”‘;

    and it works.

  6. Wilton Calderon February 27, 2015 at 11:55 pm - Reply

    Is any wordpress plugin to do that ?? thanks…

  7. Guido May 1, 2015 at 7:38 pm - Reply

    Nice post Feng,
    I’m using as follows, and works like a charm:

    function defer_parsing_of_js ( $url ) {
    if ( FALSE === strpos( $url, ‘.js’ ) ) return $url;
    if ( strpos( $url, ‘jquery.js’ ) ) return $url;
    return “$url’ defer=’defer”;
    }
    add_filter( ‘clean_url’, ‘defer_parsing_of_js’, 11, 1 );

    Tks,
    Guido

  8. Jessie Liu May 1, 2015 at 8:43 pm - Reply

    Great info! Thanks.

  9. Rich B June 25, 2015 at 2:11 pm - Reply

    Thanks for this. I used the first code snippet and my site appeared to break. The second snippet however worked like a charm.

    I have W3 Total Cache minifying the javascript and it seems to work alongside that with no issues (in manual mode).

    Thanks
    Rich

  10. Amritpal June 26, 2015 at 12:26 pm - Reply

    Thank you for the valuable post. The following worked for me:

    function defer_parsing_of_js ( $url ) {
    if ( FALSE === strpos( $url, ‘.js’ ) ) return $url;
    if ( strpos( $url, ‘jquery.js’ ) ) return $url;
    return “$url’ defer=’defer”;
    }
    add_filter( ‘clean_url’, ‘defer_parsing_of_js’, 11, 1 );

  11. Sadiq July 26, 2015 at 8:07 am - Reply

    Thanks Mate, Second code works for me and increased g-Metric Speed 🙂

    function defer_parsing_of_js ( $url ) {
    if ( FALSE === strpos( $url, ‘.js’ ) ) return $url;
    if ( strpos( $url, ‘jquery.js’ ) ) return $url;
    return “$url’ defer “;
    }
    add_filter( ‘clean_url’, ‘defer_parsing_of_js’, 11, 1 );

  12. rohim July 30, 2015 at 11:10 am - Reply

    thanks for your trick..its good for my blog.

  13. Chris August 5, 2015 at 5:32 pm - Reply

    Hi Feng, I tried both codes, but no luck. I carefully placed them in the functions.php as described but it completely removed my post content…

    Appreciate any advice, thanks!

  14. Babasultan August 12, 2015 at 1:39 pm - Reply

    The above did not affect my javascript code at all. same result

    • Feng Liu August 12, 2015 at 2:51 pm - Reply

      Try the other one in the comment section.

  15. Pourya August 24, 2015 at 3:30 am - Reply

    Can we defer .css resources as well in the same way that has been done for JS? if yes please tell me how. I’m aware of the inline css code but i’m looking for just one code to defer the unnecessary css in wordpress without plugins because sometimes plugins doesn’t work.

  16. Julie @Niackery August 25, 2015 at 12:41 am - Reply

    Hi again! I noticed that the output of the code I posted earlier wasn’t right — the defer and async attributes ended up within the src attribute (inside the quotation marks).

    I also read up a little on defer and async, and discovered that both can be used together to improve cross-browser compatibility (async takes precedence over defer when both are supported). And I learned that async shouldn’t be used if there are other script dependencies, so I removed that portion from loading in the admin, just in case. Here’s what I’ve got now, and it works like a charm:

    function defer_parsing_of_js ( $url ) {
    if ( FALSE === strpos( $url, '.js' ) ) return $url;
    if ( strpos( $url, 'jquery.js' ) ) return $url;
    if ( ! is_admin() ) {
    return $url . '" async defer onload="myinit()';
    } else {
    return $url;
    }
    }
    add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );

    But I do have one question for you, hope you don’t mind. In your examples, why use onload="myinit()" with async but not defer?

    Thanks so much for taking me down this fascinating road! Actually, I know nothing about js so I’m really happy php was the answer 😉

  17. Julie @Niackery August 25, 2015 at 12:46 am - Reply

    Well, I guess my first comment didn’t post… Just to clarify, I initially tried the defer code from the article but it caused compatibility issues with a plugin in the admin (AddQuicktag). So I used the if/else condition to load the async code in the admin; hence my explanation as to why I had changed that… Lol.

  18. rohan October 30, 2015 at 12:00 pm - Reply

    my question is how to follow your psting code instruction like i have a premium theme for my site where will i find function.php file of my theme

    • Feng Liu October 31, 2015 at 12:08 pm - Reply

      every theme should have a function.php file located at your theme folder

      • rohan November 3, 2015 at 6:13 pm - Reply

        when i pasted that code in php file my wordpress dashboard started showing error that a js script is blockimg some of the plugin resources plugin-google analytics however my defer parsing js score improves from 34 to 79

  19. danis afnita November 3, 2015 at 8:25 am - Reply

    thank you so much. it’s work!! i got A for my site after following your tutorial haha

  20. Nirmal Sarkar December 13, 2015 at 9:53 am - Reply

    Wow such a helpful article. I have been searching for defer loading of js in the internet for a few weeks but finallly found what I wanted. Actually the google pagespeed insights are itself very complicated and may just confuse a normal user.

    Anyways, i applied the codes and it did not show any specific improvements. (Maybe because I have cloudfare already). But muchas gracias for this post. 🙂

  21. Jorge December 14, 2015 at 12:17 pm - Reply

    Hi !!

    Is there any way to defer SPECIFIC .JS and not all of them? Defering all of them caused my web to behave in a wird way.

    Thanks.
    Jorge

  22. Can December 17, 2015 at 7:39 am - Reply

    I have a problem . When i put this code it works but at the same time it is blocking the site to get some body wrapper images. How can i fix it ?

    function defer_parsing_of_js ( $url ) {
    if ( FALSE === strpos( $url, ‘.js’ ) ) return $url;
    if ( strpos( $url, ‘jquery.js’ ) ) return $url;
    return “$url’ defer “;
    }
    add_filter( ‘clean_url’, ‘defer_parsing_of_js’, 11, 1 );

  23. Jonathon January 14, 2016 at 9:41 pm - Reply

    This worked 100% on my website guys.

    function defer_parsing_of_js ( $url ) {
    if ( FALSE === strpos( $url, ‘.js’ ) ) return $url;
    if ( strpos( $url, ‘jquery.js’ ) ) return $url;
    if ( ! is_admin() ) {
    return $url . ‘” async defer onload=”myinit()’;
    } else {
    return $url;
    }
    add_filter( ‘clean_url’, ‘defer_parsing_of_js’, 11, 1 );}

  24. Edema January 19, 2016 at 9:21 am - Reply

    thank you for this brilliant tutorial.

    the first code works well.

    thank you for making the process seamlessly easy

  25. Molly Kumar January 24, 2016 at 9:27 am - Reply

    Great article. I’ve been searching all over for ‘Defer Parsing of Javascript’ option which was giving my site a score of 68% (GTMetrix) and I did install the ‘“BJ Lazy Load” as per your article (I was scared to touch the .php file though)…Well my site score has increased to 83% (For the first time seeing green on GT) – Wanted to say ‘Thank You’!

  26. isak February 9, 2016 at 8:30 pm - Reply

    Is the a missing apostrophe in this line? It will not validate as it:

    return “$url’ defer “;

    I’m also getting an error message: Illegal character in query: space is not allowed. There’s a space just before “defer” —

  27. gezgin February 18, 2016 at 8:01 pm - Reply

    I tried the first code but it didn’t make a difference. Then I tried the 2. code and wow, I got my highest score at GTmetrix, %98! But then sadly I realized that my subpages were coming out blank, only homepage was displaying properly. I identified this is because of the Advanced Lazy Load plugin I’m using. Is there a way to resolve this conflict? Thanks

  28. Erion March 7, 2016 at 1:03 pm - Reply

    Hello to all,can anyone pls help me bcs im having problem to insert the code in function.php,i have try many time but not working.
    \the problem is i cant know the exact pleace to insert the code.THNX

  29. Akinola March 20, 2016 at 3:07 pm - Reply

    Hello, I copied the code in my theme function and my site went out. I was able to fix it as I saved the function php. But right now my site seems to be blank. Nothing seems to be showing on my front end at all. Please help me.

  30. Rowan G. March 28, 2016 at 3:31 pm - Reply

    The second snippet solved the trick for me :-). Much thanks for sharing. My site loads much faster now.

  31. Tito Cadallora March 29, 2016 at 9:30 pm - Reply

    Amazing job, dude! I used the same code by Juuth and my website is 50% faster!!! Thanks F Liu and thanks Juuth!!!

  32. Jonathan Jewett March 30, 2016 at 2:36 pm - Reply

    THANK YOU! I have been struggling with this issue for a week. Neither of those plugins worked correctly for my site, but the manual option you have worked perfectly!

  33. Jonathan Jewett March 30, 2016 at 2:38 pm - Reply

    For the others that are wondering where to place the code, I placed it in my functions.php file right beneath the <?php at the very beginning. Saved the file and everything worked perfect.

  34. Dave Trail March 31, 2016 at 8:49 pm - Reply

    Hi. Can you use WP Defer Loading AND BJ Lazy Load? I installed BJ Lazy Load, and it did improve the loading of my images. However, on GTMetrix, it still says that defering parsing of javascript is a priority.

  35. Sue Robbins August 5, 2016 at 10:59 am - Reply

    Hi, I have a child theme and have the following in my in my functions php file, when I place under the <?php I get errors.

    Not sure where to place the code.

    HELP!!

Leave A Comment

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.