WordPress Tips

Sometimes you need to add Defer and Async attributes to your scripts (e.g. google maps script) in WordPress.

To add the script in WordPress you need to replace this code:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>

with this, inside your theme’s functions.php file:

$gioga_map_api = YOUR_API_KEY;

wp_enqueue_script('googleapis', esc_url( add_query_arg( 'key', $gioga_map_api.'&callback=initMap', '//maps.googleapis.com/maps/api/js' )), array(), null, true );

The script loads the API from the specified URL. The callback parameter executes the initMap function after the API is completely loaded. The async attribute allows the browser to continue rendering the rest of your page while the API loads. The key parameter contains your API key.

To add Defer attribute add the following code to your theme’s functions.php file:

function gioga_add_defer_attribute($tag, $handle) {
	if ( 'googleapis' !== $handle )
	return $tag;
	return str_replace( ' src', ' defer src', $tag );
}
add_filter('script_loader_tag', 'gioga_add_defer_attribute', 10, 2);

To add Async attribute add the following code to your theme’s functions.php file:

function gioga_add_async_attribute($tag, $handle) {
	if ( 'googleapis' !== $handle )
	return $tag;
	return str_replace( ' src', ' async src', $tag );
}
add_filter('script_loader_tag', 'gioga_add_async_attribute', 10, 2);

To add Defer & Async attributes add the following code to your theme’s functions.php file:

function gioga_add_async_defer_attribute($tag, $handle) {
	if ( 'googleapis' !== $handle )
	return $tag;
	return str_replace( ' src', ' async defer src', $tag );
}
add_filter('script_loader_tag', 'gioga_add_async_defer_attribute', 10, 2);