Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Last active November 18, 2022 02:41
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save wpscholar/7b343ec2a8c52752dbc0 to your computer and use it in GitHub Desktop.
Save wpscholar/7b343ec2a8c52752dbc0 to your computer and use it in GitHub Desktop.
Class that allows you to async and defer scripts in WordPress by adding data.
<?php
class WP_Scholar_Defer_Scripts {
public static function initialize() {
add_filter( 'script_loader_tag', array( __CLASS__, 'defer_scripts' ), 10, 2 );
add_filter( 'script_loader_tag', array( __CLASS__, 'async_scripts' ), 10, 2 );
}
public static function defer_scripts( $tag, $handle ) {
if ( wp_scripts()->get_data( $handle, 'defer' ) ) {
$tag = str_replace( '></', ' defer></', $tag );
}
return $tag;
}
public static function async_scripts( $tag, $handle ) {
if ( wp_scripts()->get_data( $handle, 'async' ) ) {
$tag = str_replace( '></', ' async></', $tag );
}
return $tag;
}
}
<?php
add_action( 'login_enqueue_scripts', function () {
global $wp_scripts;
wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js' );
$wp_scripts->add_data( 'recaptcha', 'async', true );
$wp_scripts->add_data( 'recaptcha', 'defer', true );
} );
@bryanwillis
Copy link

Very cool Micah, we could probably be using wordpress wrapper functions instead of accessing the global directly. What do you think?

defer-async-scripts.php

class WP_Scholar_Defer_Scripts {
    public static function initialize() {
        add_filter( 'script_loader_tag', array( __CLASS__, 'defer_scripts' ), 10, 2 );
        add_filter( 'script_loader_tag', array( __CLASS__, 'async_scripts' ), 10, 2 );
    }
    public static function defer_scripts( $tag, $handle ) {
        if ( wp_scripts()->get_data( $handle, 'defer' ) ) {
            $tag = str_replace( '></', ' defer></', $tag );
        }
        return $tag;
    }
    public static function async_scripts( $tag, $handle ) {
        if ( wp_scripts()->get_data( $handle, 'async' ) ) {
            $tag = str_replace( '></', ' async></', $tag );
        }
        return $tag;
    }
}

usage.php

add_action( 'login_enqueue_scripts', function () {
    wp_enqueue_script( 'recaptcha', 'https://www.google.com/recaptcha/api.js' );
    wp_script_add_data( 'recaptcha', 'async', true );
    wp_script_add_data( 'recaptcha', 'defer', true );
} );

@wpscholar
Copy link
Author

Yes, indeed. I've updated the code. Thanks!

@wpscholar
Copy link
Author

This is now a full-fledged Composer friendly library: https://github.com/wpscholar/wp-async-defer-scripts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment