Last active
August 27, 2019 11:16
-
-
Save dotZak/46705dd8a6e51dbbd5f43ba68532ba2f to your computer and use it in GitHub Desktop.
WordPress `async` and `defer` tags for registered or enqueued scripts.
This file contains 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
<?php | |
/** | |
* Use in WordPress themes or plugins in order to add | |
* `async` and `defer` attributes to script tags when | |
* using `wp_enqueue_script` or `wp_register_script`. | |
*/ | |
if ( ! function_exists( 'tag_add_attribute_async' ) ) : | |
/** | |
* Add Async Attribute | |
* | |
* By adding '+async' to the $handle when registering or enqueueing the `script` | |
* tag will add the attribute `async`. | |
* | |
* @param string $tag The <script> tag for the enqueued script. | |
* @param string $handle The script's registered handle. | |
* | |
* @return string | |
*/ | |
function tag_add_attribute_async(string $tag, string $handle): string { | |
if (strpos($handle, '+async') !== false) { | |
$tag = str_replace( '<script ', '<script async ', $tag ); | |
} | |
return $tag; | |
} | |
add_filter('script_loader_tag', 'tag_add_attribute_async', 10, 2); | |
endif; // function_exists( 'tag_add_attribute_async' ) | |
if ( ! function_exists( 'tag_add_attribute_defer' ) ) : | |
/** | |
* Add Defer Attribute | |
* | |
* By adding '+defer' to the $handle when registering or enqueueing the `script` | |
* tag will add the attribute `defer`. | |
* | |
* @param string $tag The <script> tag for the enqueued script. | |
* @param string $handle The script's registered handle. | |
* | |
* @return string | |
*/ | |
function tag_add_attribute_defer(string $tag, string $handle): string { | |
if (strpos($handle, '+defer') !== false) { | |
$tag = str_replace( '<script ', '<script defer ', $tag ); | |
} | |
return $tag; | |
} | |
add_filter('script_loader_tag', 'tag_add_attribute_defer', 10, 2); | |
endif; // function_exists( 'tag_add_attribute_defer' ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment