Warning: The type attribute is unnecessary for JavaScript resources.

By default if you check (w3 validator) any site, that based on WordPress you can see multiple warnings relating to scripts and styles tags attributes. The thing is the service recommended remove type=’text/javascript’ from the scripts tags and type=’text/css’ from the styles tags.

Remove type attribute from script and style tags added by WordPress

Problem: How to fix "Warning: The type attribute is unnecessary for JavaScript resources."?

Solution: At the first I found this solution:

add_action( 'wp_loaded', 'remove_type_attr' );

function prefix_output_buffer_start() {
    ob_start( 'prefix_output_callback' );
}
	
add_action( 'shutdown', 'prefix_output_buffer_end' );

function prefix_output_buffer_end() {
	ob_end_flush();
}
	
function prefix_output_callback( $buffer ) {
	return preg_replace( "%[ ]type=[\'\"]text\/(javascript|css)[\'\"]%", '', $buffer );
}

then this (it's variant more concise, than previous):

add_filter( 'style_loader_tag', 'remove_type_attr', 10, 2 );
add_filter( 'script_loader_tag', 'remove_type_attr', 10, 2 );
	
function sj_remove_type_attr( $tag ) {
	return preg_replace( "/ type=['\"]text\/(javascript|css)['\"]/", '', $tag );
}

But both solutions have one common disadvantage - if we use wp_localize_script for pass variables from back-end to front-end our solutions doesn't work, and one tag script will has attribute. But however there's a way out:

add_action( 'template_redirect', 'remove_type_attr' );
	
function remove_type_attr() {
	ob_start( function ( $buffer ) {
		return preg_replace( "%[ ]type=['\"]text\/(javascript|css)['\"]%", '', $buffer );
	} );
}

Source:

  1. https://stackoverflow.com/questions/51709618/remove-type-text-javascript-from-contact-form-7-tags/

Leave Comment

Your email address will not be published. Required fields are marked *