Make WordPress Core


Ignore:
Timestamp:
09/12/2023 12:04:15 AM (9 months ago)
Author:
westonruter
Message:

Bundled Themes: Use defer loading strategy for theme scripts.

  • Add defer loading strategy for all frontend end-user theme scripts (excluding Customizer preview).
  • Move scripts to the head which relate to the initial page viewport to ensure they start loading earlier and execute sooner while still not blocking rendering.
  • Update Twenty Twenty's script loader (TwentyTwenty_Script_Loader) to support core's built-in script loading strategies (#12009), while also retaining backwards-compatibility for child themes that may set async and defer script data.
  • Update the main script loading strategy in Twenty Twenty from async to defer for better performance on repeat page views, since when an async script is cached it will block rendering.

Props westonruter, flixos90, sabernhardt.
Fixes #59316.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-content/themes/twentytwenty/functions.php

    r56548 r56556  
    136136     */
    137137    $loader = new TwentyTwenty_Script_Loader();
    138     add_filter( 'script_loader_tag', array( $loader, 'filter_script_loader_tag' ), 10, 2 );
     138    if ( version_compare( $GLOBALS['wp_version'], '6.3', '<' ) ) {
     139        add_filter( 'script_loader_tag', array( $loader, 'filter_script_loader_tag' ), 10, 2 );
     140    } else {
     141        add_filter( 'print_scripts_array', array( $loader, 'migrate_legacy_strategy_script_data' ), 100 );
     142    }
    139143}
    140144
     
    212216    }
    213217
    214     wp_enqueue_script( 'twentytwenty-js', get_template_directory_uri() . '/assets/js/index.js', array(), $theme_version );
    215     wp_script_add_data( 'twentytwenty-js', 'async', true );
     218    wp_enqueue_script(
     219        'twentytwenty-js',
     220        get_template_directory_uri() . '/assets/js/index.js',
     221        array(),
     222        $theme_version,
     223        array(
     224            'in_footer' => false, // Because involves header.
     225            'strategy'  => 'defer',
     226        )
     227    );
    216228}
    217229
Note: See TracChangeset for help on using the changeset viewer.