Skip to content

Instantly share code, notes, and snippets.

@thierrypigot thierrypigot/functions.php
Last active Jul 15, 2019

Embed
What would you like to do?
Defer WordPress javascript
<?php
// Show javascript handle
add_filter( 'script_loader_tag', 'wearewp_add_script_handle', 10, 3 );
function wearewp_add_script_handle( $tag, $handle, $src ) {
return str_replace( '<script', sprintf(
'<script data-handle="%1$s"',
esc_attr( $handle )
), $tag );
}
// Add defer and async to selected handle
add_filter('script_loader_tag', 'wearewp_add_async_defer_attribute', 10, 2);
function wearewp_add_async_defer_attribute($tag, $handle) {
$to_defer = array(
// 'jquery-core' => 'defer',
'jquery-ui-core' => 'async defer',
'jquery-ui-datepicker' => 'async defer',
'jquery-ui-accordion' => 'async defer',
'jquery-ui-tabs' => 'async defer',
'jquery-effects-core' => 'async defer',
'prettyPhoto' => 'async defer',
'owlcarousel' => 'async defer',
'sohohotel_custom_js' => 'async defer',
'jquery-migrate' => 'defer',
'front-js-na' => 'async defer',
'googlesearch' => 'async defer',
'fontawesomemarkers' => 'async defer',
'wpml-legacy-dropdown-0' => 'async defer',
'wpml-browser-redirect' => 'async defer',
'cookie-notice-front' => 'async defer',
'jquery-ui-widget' => 'async defer',
'jquery-ui-tabs' => 'async defer',
'jquery-effects-core' => 'async defer',
'et_monarch-idle' => 'async defer',
'et_monarch-custom-js' => 'async defer',
'wpb_composer_front_js' => 'async defer',
'et-core-common' => 'async defer',
'vc_waypoints' => 'async defer',
);
if ( array_key_exists($handle,$to_defer) ){
return str_replace( ' src', ' '. $to_defer[$handle] .' src', $tag );
}else{
return $tag;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.