Skip to content
This repository has been archived by the owner on Jan 15, 2019. It is now read-only.

Adds async/defer capability to JavaScript loading #39

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ function twentynineteen_content_width() {
function twentynineteen_scripts() {
wp_enqueue_style( 'twentynineteen-style', get_stylesheet_uri() );

wp_enqueue_script( 'twentynineteen-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );
wp_enqueue_script( 'twentynineteen-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', false );

if ( is_singular() && twentynineteen_can_show_post_thumbnail() ) {
wp_add_inline_style( 'twentynineteen-style', twentynineteen_header_featured_image_css() );
Expand Down
33 changes: 32 additions & 1 deletion inc/template-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,37 @@ function twentynineteen_body_classes( $classes ) {
}
add_filter( 'body_class', 'twentynineteen_body_classes' );

/**
* Adds async/defer attributes to enqueued / registered scripts.
*
* If #12009 lands in WordPress, this function can no-op since it would be handled in core.
*
* @link https://core.trac.wordpress.org/ticket/12009
* @param string $tag The script tag.
* @param string $handle The script handle.
* @return array
*/
function twentynineteen_filter_script_loader_tag( $tag, $handle ) {

foreach ( array( 'async', 'defer' ) as $attr ) {
if ( ! wp_scripts()->get_data( $handle, $attr ) ) {
continue;
}

// Prevent adding attribute when already added in #12009.
if ( ! preg_match( ":\s$attr(=|>|\s):", $tag ) ) {
$tag = preg_replace( ':(?=></script>):', " $attr", $tag, 1 );
}

// Only allow async or defer, not both.
break;
}

return $tag;
}

add_filter( 'script_loader_tag', 'twentynineteen_filter_script_loader_tag', 10, 2 );

/**
* Add a pingback url auto-discovery header for single posts, pages, or attachments.
*/
Expand Down Expand Up @@ -187,4 +218,4 @@ function twentynineteen_get_discussion_data() {
'responses' => $responses, /* Number of responses, excluding responses from current user. */
);
return $discussion;
}
}