Açıklama Yok

class-twentytwenty-script-loader.php 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. * @since Twenty Twenty 1.0
  18. */
  19. class TwentyTwenty_Script_Loader {
  20. /**
  21. * Adds async/defer attributes to enqueued / registered scripts.
  22. *
  23. * If #12009 lands in WordPress, this function can no-op since it would be handled in core.
  24. *
  25. * @since Twenty Twenty 1.0
  26. *
  27. * @link https://core.trac.wordpress.org/ticket/12009
  28. *
  29. * @param string $tag The script tag.
  30. * @param string $handle The script handle.
  31. * @return string Script HTML string.
  32. */
  33. public function filter_script_loader_tag( $tag, $handle ) {
  34. foreach ( array( 'async', 'defer' ) as $attr ) {
  35. if ( ! wp_scripts()->get_data( $handle, $attr ) ) {
  36. continue;
  37. }
  38. // Prevent adding attribute when already added in #12009.
  39. if ( ! preg_match( ":\s$attr(=|>|\s):", $tag ) ) {
  40. $tag = preg_replace( ':(?=></script>):', " $attr", $tag, 1 );
  41. }
  42. // Only allow async or defer, not both.
  43. break;
  44. }
  45. return $tag;
  46. }
  47. }
  48. }