Skip to content

Instantly share code, notes, and snippets.

@georgestephanis
Last active May 21, 2017 05:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgestephanis/2a84bc55ad23f4dec2cf2464109add59 to your computer and use it in GitHub Desktop.
Save georgestephanis/2a84bc55ad23f4dec2cf2464109add59 to your computer and use it in GitHub Desktop.
<?php
/**
* The only point of this is to add the `defer` attribute to
* a script (in this case, jQuery) to test with.
*/
add_action( 'wp_print_scripts', function() {
wp_script_add_data( 'jquery-core', 'defer', true );
} );
/**
* This is the meat and potatoes -- checks for defer attribute and adds it to the tag.
*/
add_filter( 'script_loader_tag', function( $tag, $handle, $src ) {
$scripts = wp_scripts();
$obj = $scripts->registered[ $handle ];
if ( ! empty( $obj->extra['defer'] ) ) {
$tag = str_replace( " src='$src'>", " src='$src' defer>", $tag );
}
return $tag;
}, 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment