jcicero518
6/5/2018 - 10:56 PM

WP Script Tag Async / Defer

Simple way to preprocess script tags enqueued in WP. Shows a conditional that checks for the exact name of a script handle and a check for multiple similar ones.

<?php
/**
	 * Filter output of script tags before they are "printed" to
	 * the screen. Useful for flagging deferred or async loading
	 * 
	 * @param string $tag
	 * @param string $handle 
	 * - matches first param of wp_register_script or
	 * - wp_enqueue_script
	 * @param $src
	 *
	 * @return mixed
	 */
	public function modifyScriptTags( $tag, $handle, $src ) {
		if ( $handle === 'specific-handle' || ( strpos( $handle, 'common-handles-' ) !== FALSE ) ) {
			$tag = str_replace( "<script type='text/javascript'", "<script type='text/javascript' defer ", $tag );
		}
		return $tag;
	}
	
	// example usage outside of namespace / class
	add_filter( 'script_loader_tag', 'modifyScriptTags', 10, 3 );