Add data-pagespeed-no-defer to scripts

We provide the code snippets and content on this page without any guarantee or support. In most cases, these pages are created on requests or based on individual solutions sent to us by other users. After it was published, we are only reviewing the code and content when we are made aware of an issue. Please let us know if you find one.

Please only use the codes if you understand them and know how to add custom code to your WordPress site.

data-pagespeed-no-defer is a custom attribute by Google for their PageSpeed module. Some services might still honor it when trying to optimize scripts loading on your website.

Deferring certain scripts used by Advanced Ads could lead to a delay in the ads visibility and therefore decrease your ad revenue.

The following code snippet is just an example on how to exclude the main script in Advanced Ads and Advanced Ads Pro from deferring. The service you are using might have an interface to better exclude scripts.

Depending on how they order scripts, it might be needed to add data-pagespeed-no-defer to other scripts, too, like jQuery.

 * Filters the HTML script tag of an enqueued script to add `data-pagespeed-no-defer` attribute.
 * @param string $html   The `<script>` tag for the enqueued script.
 * @param string $handle The script's registered handle.
 * @return string
add_filter( 'script_loader_tag', function( $html, $handle ) {
	if ( ! in_array( $handle, array( 'advanced-ads-advanced-js', 'advanced-ads-pro/cache_busting' ), true ) ) {
		return $html;

	return str_replace( 'src=', 'data-pagespeed-no-defer src=', $html );
}, 10, 2 );Code language: PHP (php)

Make it better

Increase your ad management skills without spending more time.
Join over 150,000 publishers and AdOpts increasing their ad revenue.