Skip to content

Instantly share code, notes, and snippets.

@mishterk
Last active March 17, 2023 09:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishterk/6b7a4d6e5a91086a5a9b05ace304b5ce to your computer and use it in GitHub Desktop.
Save mishterk/6b7a4d6e5a91086a5a9b05ace304b5ce to your computer and use it in GitHub Desktop.
How to mark your WordPress scripts as async or defer. For more info see https://philkurth.com.au/tips/how-to-set-defer-or-async-attributes-on-enqueued-script-tags-in-wordpress/
<?php
add_action( 'wp_enqueue_scripts', function () {
wp_register_script( 'my-script', get_stylesheet_directory_uri() . '/assets/js/my-script.js' );
wp_enqueue_script( 'my-script' );
} );
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'my-script' !== $handle ) {
return $tag;
}
return str_replace( ' src', ' defer src', $tag ); // defer the script
//return str_replace( ' src', ' async src', $tag ); // OR async the script
//return str_replace( ' src', ' async defer src', $tag ); // OR do both!
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment