How To Add Defer & Async Attributes To Scripts Without A Plugin
Example Code.
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'contact-form-7' !== $handle )
return $tag;
return str_replace( ' src', ' defer="defer" src', $tag );
}, 10, 2 );
The above code uses an example script handle from Contact Form 7. You can easily expand this but to add scripts you need to get the script handle (for themes this is the handle you used when registering the file and used to enqueue it). If you are a user, you can install various plugins that can help you find this such as:
Once you located it, adding the above code for multiple files is pretty straightforward.
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'contact-form-7' || 'some-js-file' !== $handle )
return $tag;
return str_replace( ' src', ' defer="defer" src', $tag );
}, 10, 2 );
Essentially all you need to do is the following:
- Add the ||.
- Make your filename wrapped in ' '.
Scott Hartley
Founder & CEO, Sert Media
Founder and CEO of Sert Media, a Nashville-based digital marketing agency. Scott has spent over 15 years helping businesses grow through SEO, web performance optimization, and strategic digital marketing. His deep expertise in WordPress development, site speed, and technical SEO has guided hundreds of brands toward measurable results. When he's not auditing Core Web Vitals or refining campaign strategies, he's writing about the tools, techniques, and trends shaping the modern web.
Related Articles
How to Add Security Headers to WordPress Using Cloudflare Transform Rules
If you've ever run your WordPress site through securityheaders.com and gotten a D or F…
Use This Cloudflare Rule To Reduce Plugin Hack Attempts
Cloudflare Firewall Rules give you a lot of flexibility in further protecting your website. Here…
Set Up Cloudflare's Automatic Platform Optimization Feature
Automatic Platform Optimization (APO) is a new feature from Cloudflare that allows you to cache…