class-twentytwenty-script-loader.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. /**
  3. * Javascript Loader Class
  4. *
  5. * Allow `async` and `defer` while enqueuing Javascript.
  6. *
  7. * Based on a solution in WP Rig.
  8. *
  9. * @package WordPress
  10. * @subpackage Twenty_Twenty
  11. * @since Twenty Twenty 1.0
  12. */
  13. if ( ! class_exists( 'TwentyTwenty_Script_Loader' ) ) {
  14. /**
  15. * A class that provides a way to add `async` or `defer` attributes to scripts.
  16. */
  17. class TwentyTwenty_Script_Loader {
  18. /**
  19. * Adds async/defer attributes to enqueued / registered scripts.
  20. *
  21. * If #12009 lands in WordPress, this function can no-op since it would be handled in core.
  22. *
  23. * @link https://core.trac.wordpress.org/ticket/12009
  24. *
  25. * @param string $tag The script tag.
  26. * @param string $handle The script handle.
  27. * @return string Script HTML string.
  28. */
  29. public function filter_script_loader_tag( $tag, $handle ) {
  30. foreach ( array( 'async', 'defer' ) as $attr ) {
  31. if ( ! wp_scripts()->get_data( $handle, $attr ) ) {
  32. continue;
  33. }
  34. // Prevent adding attribute when already added in #12009.
  35. if ( ! preg_match( ":\s$attr(=|>|\s):", $tag ) ) {
  36. $tag = preg_replace( ':(?=></script>):', " $attr", $tag, 1 );
  37. }
  38. // Only allow async or defer, not both.
  39. break;
  40. }
  41. return $tag;
  42. }
  43. }
  44. }