diff --git a/functions.php b/functions.php index 6e034e281..9a9580eb8 100644 --- a/functions.php +++ b/functions.php @@ -118,6 +118,9 @@ function twentytwenty_theme_support() { // Custom comment walker require get_template_directory() . '/parts/classes/class-comment-walker.php'; +// Handle JavaScript loading +require get_template_directory() . '/parts/classes/class-script-loader.php'; + /** * Register and Enqueue Styles */ @@ -159,6 +162,7 @@ function twentytwenty_register_scripts() { $js_dependencies = array( 'jquery' ); wp_enqueue_script( 'twentytwenty-construct', get_template_directory_uri() . '/assets/js/construct.js', $js_dependencies, $theme_version ); + wp_script_add_data( 'twentytwenty-construct', 'async', true ); } add_action( 'wp_enqueue_scripts', 'twentytwenty_register_scripts' ); diff --git a/parts/classes/class-script-loader.php b/parts/classes/class-script-loader.php new file mode 100644 index 000000000..4eb2da6cd --- /dev/null +++ b/parts/classes/class-script-loader.php @@ -0,0 +1,39 @@ +get_data( $handle, $attr ) ) { + continue; + } + // Prevent adding attribute when already added in #12009. + if ( ! preg_match( ":\s$attr(=|>|\s):", $tag ) ) { + $tag = preg_replace( ':(?=>):', " $attr", $tag, 1 ); + } + // Only allow async or defer, not both. + break; + } + return $tag; + } + +} + +$loader = new TwentyTwenty_Script_Loader; +add_filter( 'script_loader_tag', [ $loader, 'filter_script_loader_tag' ], 10, 2 );