Recently I worked on one website in which client wants to fix all the Errors and Warning that display in W3 validator. So I checked many warning that show these two issues:
"The type attribute is unnecessary for JavaScript resources."
"The type attribute for the style element is not needed and should be omitted."
But the type attributes automatically adds when we include scripts in our theme. Also its very difficult to manual removed "type" attribute because we have lots of scripts and styles from theme as well as from plugins. So I found following 2 solutions that works great for me.
First Method:
For this I used two hooks:
style_loader_tag – HTML link tag of an enqueued style
script_loader_tag – Html ling tag of the enqueued script
So I created an function called custom_remove_type_attr that with a reg expression remove the type attribute from WordPress loaded JavaScript and Styles tags.
After that i have added two filters one for the style tag hook and the other one for the script hook.
You need to add this following code in your functions.php file
add_filter('style_loader_tag', 'custom_remove_type_attr', 10, 2);
add_filter('script_loader_tag', 'custom_remove_type_attr', 10, 2);
function custom_remove_type_attr($tag, $handle) {
return preg_replace( "/type=['\"]text\/(javascript|css)['\"]/", '', $tag );
}
Second Method:
If above code not works you can try this following code. I tested both codes and both works well.
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 );
}
After adding this code you will see all <script type="text/javascript"> replaced with <script>.
Now you will see all warnings is resolved.
0 Comments