Async or Defer JavaScript Files in WordPress

There are a lot of articles out there about how to async or defer scripts in WordPress, but they assume you’ll be writing all the code or using one of the bloated plugins to make it happen.

In my case, I just needed the ability to async or defer a few scripts in a custom plugin or theme. Sure, I could add all the filters every time to make that work, but I’m a programmer. Why should I have to constantly write the same code over and over again? Why not create a simple module to handle this for me and allow me to async and defer scripts in a truly WordPress way? So I did just that.

Introducing the WordPress Async/Defer Scripts Module

A Composer library for asynchronously loading or deferring scripts in WordPress. View on GitHub or Packagist.

Requirements

  • PHP 5.3+
  • WordPress 4.2+

Installation

Add the module to your code base via Composer:

composer require wpscholar/wp-async-defer-scripts

Be sure to require the Composer autoloader in your project:

<?php

require __DIR__ . '/vendor/autoload.php';

Usage

Asynchronously load a script using the wp_scripts()->add_data() method:

<?php

add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js' );
    wp_scripts()->add_data( 'recaptcha', 'async', true );
} );

Defer loading of a script using the wp_scripts()->add_data() method:

<?php

add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js' );
    wp_scripts()->add_data( 'recaptcha', 'defer', true );
} );

Initialization

In most cases, you can simply follow the installation instructions and things will just work. However, if you are including this library outside of a WordPress plugin or theme, you may have to manually initialize the class:

<?php

wpscholar\WordPress\AsyncDeferScripts::initialize();

Conclusion

I’d love to see simple async and defer functionality added to WordPress core, but in the meantime, this has worked out quite well for my own personal projects and I thought I’d share it with you. What do you think?

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Up Next:

WordPress Post Expiration Module

WordPress Post Expiration Module