Created
May 21, 2019 13:14
-
-
Save deeman/838fb27233b847ad5a7c01fda7e8ce3e to your computer and use it in GitHub Desktop.
Add async or defer to enqueue WordPress scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Add async, defer, or other attributes to enqueue WordPress scripts | |
| * Add async attributes to enqueued scripts where needed. | |
| * The ability to filter script tags was added in WordPress 4.1 for this purpose. | |
| */ | |
| function my_async_scripts( $tag, $handle, $src ) { | |
| // the handles of the enqueued scripts we want to async | |
| $async_scripts = array( 'some-script', 'another-script' ); | |
| if ( in_array( $handle, $async_scripts ) ) { | |
| return '<script type="text/javascript" src="' . $src . '" async="async"></script>' . "\n"; | |
| } | |
| return $tag; | |
| } | |
| add_filter( 'script_loader_tag', 'my_async_scripts', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment