Skip to content

Instantly share code, notes, and snippets.

@annalinneajohansson
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save annalinneajohansson/2df10617fddd0d9e71f0 to your computer and use it in GitHub Desktop.

Select an option

Save annalinneajohansson/2df10617fddd0d9e71f0 to your computer and use it in GitHub Desktop.
Add defer to enqueued javascripts in WordPress
<?php
// clean_url can be used in versions prior to 4.1
add_filter( 'clean_url', function( $url ) {
if( is_admin() ) {
return $url;
}
if ( FALSE === strpos( $url, '.js' ) ) {
return $url;
}
return "$url' defer='defer";
}, 11, 1 );
<?php
// script_loader_tag hook added in WP 4.1
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if( is_admin() ) {
return $tag;
}
return str_replace( ' src', ' defer="defer" src', $tag );
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment