The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Defer a Specific WordPress Script

Shared by Hiral solanki · September 9, 2026 · @script_loader_tag

33 views
1 upvote
Back to Snippets
/**
 * Add defer attribute to a specific script.
 *
 * @param string $tag    Script HTML.
 * @param string $handle Script handle.
 * @param string $src    Script source.
 * @return string
 */
function mytheme_defer_script( $tag, $handle, $src ) {

	$defer_scripts = array(
		'mytheme-main-js',
	);

	if ( in_array( $handle, $defer_scripts, true ) ) {
		return '<script src="' . esc_url( $src ) . '" defer></script>';
	}

	return $tag;
}

add_filter( 'script_loader_tag', 'mytheme_defer_script', 10, 3 );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments

Proudly supported by