Have a WordPress site with some render blocking JavaScript? Are you using a plugin like Autoptimize that can’t aggregate/concatenate and therefore cannot defer external, 3rd-party JavaScript? Eliminate it with this code snippet for better real world performance and better grades on tools like PageSpeed Insights! Copy and paste this code snippet — in plain text — to your functions.php file, or, add it with a plugin like Code Snippets and adjust accordingly. NOTE: defer=”defer” can also be async=”async”, test both with WebPageTest.org to see which results in the best real-world performance. This code will work for all properly enqueued JavaScript files.
The fastest possible version of your website is no longer optional. We can help! Learn more…
/*Function to defer or asynchronously load scripts*/ function js_async_attr($tag){ # Do not add defer or async attribute to these scripts $scripts_to_exclude = array('script1.js', 'script2.js', 'script3.js'); foreach($scripts_to_exclude as $exclude_script){ if(true == strpos($tag, $exclude_script ) ) return $tag; } # Defer or async all remaining scripts not excluded above return str_replace( ' src', ' defer="defer" src', $tag ); } add_filter( 'script_loader_tag', 'js_async_attr', 10 );
RECENT POSTS
Comments 9
Thanks a lot for this script you just posted
thanks for information
WOW!! Thanks!!
Can you help with the CSS to?
Is there something to add to the script?
Thanks for this, really help me.
More than a time, I search this answer on google, at last finally found out through your website.
Great. Thanx for sharing
博客大好,让人忘不了!
Great site and snippets – so you do not have to use (unsecured) plugins. Clap, Clap, Clap
I am using this snippet but, if being use as is, this breaks my admin console – nothing loads…
So enclosing it in
if ( !is_admin() ) {
}
did the trick for me!
Hope this will help ppl out there
Thank you for your content and code snippets! We are really about optimizing websites for speed. This site is a great help! Appreciate all your work!
Thank you!
This is much more useful that the available plugins.