最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - Remove type attribute from script and style tags added by WordPress

programmeradmin2浏览0评论
Warning: The type attribute is unnecessary for JavaScript resources.
    From line 10, column 146; to line 10, column 176
    feed/" /> <script type="text/javascript">window
   
 Warning: The type attribute for the style element is not needed and should be omitted.
    From line 11, column 1798; to line 11, column 1820
    </script> <style type="text/css">img.wp
    
Warning: The type attribute for the style element is not needed and should be omitted.
    From line 23, column 193; to line 23, column 251
    a='all' /><style id='kirki-styles-global-inline-css' type='text/css'>.envel
    
Warning: The type attribute is unnecessary for JavaScript resources.
    From line 23, column 905; to line 23, column 1010
    }</style> <script async type="text/javascript" src="http://....../wp-content/cache/minify/df983.js"></scri
    
Warning: The type attribute for the style element is not needed and should be omitted.
    From line 70, column 126; to line 70, column 167
    70.png" /><style type="text/css" id="wp-custom-css">@media
    
Warning: The type attribute is unnecessary for JavaScript resources.
    From line 441, column 156; to line 441, column 261
    iv></div> <script defer type="text/javascript" src="http://......./wp-content/cache/minify/26938.js"></scri
    
Warning: The type attribute is unnecessary for JavaScript resources.
    From line 441, column 272; to line 441, column 302
    </script> <script type='text/javascript'>/*  */
    
Warning: The type attribute is unnecessary for JavaScript resources.
    From line 443, column 17; to line 443, column 122
    </script> <script defer type="text/javascript" src="http://......../wp-content/cache/minify/6ce07.js"></scri

These errors are some new introduction by W3C and they have started to creep in last 3-4 days only.

We enqueue scripts like this →

wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true );
    wp_enqueue_script( 'custom-js' );

Can we fix this from the above enqueuing method somehow?

Update →

these are the actual errors. In the red box are coming from W3 total cache.

Warning: The type attribute is unnecessary for JavaScript resources.
    From line 10, column 146; to line 10, column 176
    feed/" /> <script type="text/javascript">window
   
 Warning: The type attribute for the style element is not needed and should be omitted.
    From line 11, column 1798; to line 11, column 1820
    </script> <style type="text/css">img.wp
    
Warning: The type attribute for the style element is not needed and should be omitted.
    From line 23, column 193; to line 23, column 251
    a='all' /><style id='kirki-styles-global-inline-css' type='text/css'>.envel
    
Warning: The type attribute is unnecessary for JavaScript resources.
    From line 23, column 905; to line 23, column 1010
    }</style> <script async type="text/javascript" src="http://....../wp-content/cache/minify/df983.js"></scri
    
Warning: The type attribute for the style element is not needed and should be omitted.
    From line 70, column 126; to line 70, column 167
    70.png" /><style type="text/css" id="wp-custom-css">@media
    
Warning: The type attribute is unnecessary for JavaScript resources.
    From line 441, column 156; to line 441, column 261
    iv></div> <script defer type="text/javascript" src="http://......./wp-content/cache/minify/26938.js"></scri
    
Warning: The type attribute is unnecessary for JavaScript resources.
    From line 441, column 272; to line 441, column 302
    </script> <script type='text/javascript'>/*  */
    
Warning: The type attribute is unnecessary for JavaScript resources.
    From line 443, column 17; to line 443, column 122
    </script> <script defer type="text/javascript" src="http://......../wp-content/cache/minify/6ce07.js"></scri

These errors are some new introduction by W3C and they have started to creep in last 3-4 days only.

We enqueue scripts like this →

wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true );
    wp_enqueue_script( 'custom-js' );

Can we fix this from the above enqueuing method somehow?

Update →

these are the actual errors. In the red box are coming from W3 total cache.

Share Improve this question edited Jun 15, 2020 at 8:21 CommunityBot 1 asked Dec 5, 2017 at 19:05 WordCentWordCent 1,8776 gold badges34 silver badges60 bronze badges 5
  • 5 the W3C validator rarely returns as errorless for Wordpress sites or any popular cms. it seems to be getting worse-and-worse every year. The validator (imho) should be used as tools for revealing some basic errors (like forgetting alt tags, or forgetting to close a tag), but shouldn't be looked at as a standard as it used to be. – David Sword Commented Dec 5, 2017 at 19:11
  • they have introduced it after December 2, 017. before that my theme was error/warning free. There should be some way to get rid of them. – WordCent Commented Dec 5, 2017 at 19:16
  • 2 look into the script_loader_tag hook, you might be able to do an str_replace() to remove them. – David Sword Commented Dec 5, 2017 at 20:18
  • Worth pointing out that these are just warnings, not errors. Your site will still validate. – swissspidy Commented Jan 26, 2018 at 8:45
  • You can check following answer also -- stackoverflow/a/53380692/2611955 – Jahirul Islam Mamun Commented Sep 23, 2019 at 5:24
Add a comment  | 

12 Answers 12

Reset to default 45

WordPress 5.3 introduces a considerably simpler way to achieve this. By registering theme support for HTML 5 for script and style, the type="" attribute will be omitted:

add_action(
    'after_setup_theme',
    function() {
        add_theme_support( 'html5', [ 'script', 'style' ] );
    }
);

You can remove the type='*' attributes and values from wp_enqueue'ed scripts and styles, using respective *_loader_tag hooks.

The following worked for me:

add_action( 'wp_enqueue_scripts', 'myplugin_enqueue' );

function myplugin_enqueue() {
    // wp_register_script(...
    // wp_enqueue_script(...
}


add_filter('style_loader_tag', 'myplugin_remove_type_attr', 10, 2);
add_filter('script_loader_tag', 'myplugin_remove_type_attr', 10, 2);

function myplugin_remove_type_attr($tag, $handle) {
    return preg_replace( "/type=['\"]text\/(javascript|css)['\"]/", '', $tag );
}

Got this from the soil / roots plugin. did the job for the most part.

    add_filter( 'style_loader_tag',  'clean_style_tag'  );
add_filter( 'script_loader_tag', 'clean_script_tag'  );

/**
 * Clean up output of stylesheet <link> tags
 */
function clean_style_tag( $input ) {
    preg_match_all( "!<link rel='stylesheet'\s?(id='[^']+')?\s+href='(.*)' type='text/css' media='(.*)' />!", $input, $matches );
    if ( empty( $matches[2] ) ) {
        return $input;
    }
    // Only display media if it is meaningful
    $media = $matches[3][0] !== '' && $matches[3][0] !== 'all' ? ' media="' . $matches[3][0] . '"' : '';

    return '<link rel="stylesheet" href="' . $matches[2][0] . '"' . $media . '>' . "\n";
}

/**
 * Clean up output of <script> tags
 */
function clean_script_tag( $input ) {
    $input = str_replace( "type='text/javascript' ", '', $input );

    return str_replace( "'", '"', $input );
}

The style_loader_tag and script_loader_tag approaches above look like they should work for whatever markup Wordpress is generating, in cases where the theme/plugin is using the proper enqueue functions.

If you have offending plugins that don't cooperate (IIRC Jetpack is/was an offender unless a newer version since my recollection has revised this!), and you are adamant about solving this issue despite the fact that your visitors are not likely to be impacted in any way (their browser will render the page fine!), you can always go all-out and use output buffering:

add_action('wp_loaded', 'output_buffer_start');
function output_buffer_start() { 
    ob_start("output_callback"); 
}

add_action('shutdown', 'output_buffer_end');
function output_buffer_end() { 
    ob_end_flush(); 
}

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

Be warned that while this is a solution, it isn't very efficient. You'd be running preg_replace() on the entire "final" output from Wordpress before it gets sent to the client's browser, for every request.

Output buffering is turned on at the start (wp_loaded hook), i.e. right as wp + theme + plugins + etc are fully loaded, and is turned off at the last moment (shutdown hook) which fires just before PHP shuts down execution. The regex must work through everything, and that could be a lot of content!

The style_loader_tag and script_loader_tag approaches above only run the regex on a very small string (the tag itself) so the performance impact is negligible.

I suppose if you had relatively static content and used a caching layer you could try to mitigate the performance concern.

php manual references:

  • http://php/manual/en/function.ob-start.php
  • http://php/manual/en/function.ob-end-flush.php

This helped me a lot:

add_filter('script_loader_tag', 'clean_script_tag');
  function clean_script_tag($input) {
  $input = str_replace("type='text/javascript' ", '', $input);
  return str_replace("'", '"', $input);
}

Thanks to css-tricks (LeoNovais): https://css-tricks/forums/topic/clean-up-script-tags-in-wordpress/#post-246425

According to code in script-loader.php type attribute is omitted when html5 theme support is added with script and style arguments.

See below links:

  • https://build.trac.wordpress/browser/tags/5.3/wp-includes/script-loader.php#L2576
  • https://build.trac.wordpress/browser/tags/5.3/wp-includes/script-loader.php#L2758
function yourthemeprefix_theme_supportt() {
    add_theme_support(
        'html5',
        array(
            'script', // Fix for: The "type" attribute is unnecessary for JavaScript resources.
            'style',  // Fix for: The "type" attribute for the "style" element is not needed and should be omitted.
        )
    );
}
add_action( 'after_setup_theme', 'yourthemeprefix_theme_support' );

Building off of @realmag77. This will leverage the Autoptimize plugin to be able to filter out ALL type attributes but not break if it's not installed and activated. The fallback works fine but those scripts and stylesheets loaded through plugins won't be filtered. I don't know how else to filter them but through using the Autoptimize portion.

/* ==========================================
   Remove type attribute on JS/CSS
   (requires Autoptimize plugin and Optimize HTML checked)
   but with fallback just in case
========================================== */

// If Autoptimize is installed and activated, remove type attributes for all JS/CSS
if ( is_plugin_active( 'autoptimize/autoptimize.php' ) ) {

    add_filter('autoptimize_html_after_minify', function($content) {

        $site_url = home_url();
        $content = str_replace("type='text/javascript'", '', $content);
        $content = str_replace('type="text/javascript"', '', $content);

        $content = str_replace("type='text/css'", '', $content);
        $content = str_replace('type="text/css"', '', $content);

        $content = str_replace($site_url . '/wp-includes/js', '/wp-includes/js', $content);
        $content = str_replace($site_url . '/wp-content/cache/autoptimize', '/wp-content/cache/autoptimize', $content);
        $content = str_replace($site_url . '/wp-content/themes/', '/wp-content/themes/', $content);
        $content = str_replace($site_url . '/wp-content/uploads/', '/wp-content/uploads/', $content);
        $content = str_replace($site_url . '/wp-content/plugins/', '/wp-content/plugins/', $content);

        return $content;

    }, 10, 1);

} else {

    // Fallback to remove type attributes except for those loaded through plugins
    add_filter('style_loader_tag', 'pss_remove_type_attr', 10, 2);
    add_filter('script_loader_tag', 'pss_remove_type_attr', 10, 2);
    function pss_remove_type_attr($tag, $handle) {
        return preg_replace( "/type=['\"]text\/(javascript|css)['\"]/", '', $tag );
    }
}
add_action('wp_loaded', 'prefix_output_buffer_start');
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 );
}

You can use the functions below to remove type attributes from link and script tags.

Paste the function below in functions.php for removing the type=text/css from link tags

/* Remove the attribute " 'type=text/css' " from stylesheet  */
function wpse51581_hide_type($src) {
    return str_replace("type='text/css'", '', $src);
}
add_filter('style_loader_tag', 'wpse51581_hide_type');

===========================================================================

Paste the function below in functions.php for removing the type='text/javascript' from script

//* Remove type tag from script and style
add_filter('script_loader_tag', 'codeless_remove_type_attr', 10, 2);
function codeless_remove_type_attr($tag, $handle) {
    return preg_replace( "/type=['\"]text\/(javascript|css)['\"]/", '', $tag );
}

Well, because I've tried tons of other codes and the ones mentioned here, There are still traces of the text/javascript from WordPress core files and also from other plugin and inline javascript codes. After testing this code, everything has been resolved:

// Remove w3 validator regarding "text/javascript"
add_action('wp_loaded', 'prefix_output_buffer_start');
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 );
}

Hope it can help some :)

Thank you

If you are experiencing this with WP Fastest Cache you can delete type attribute manually in the plugin PHP script, this should work with other plugins too, but I don't know files where they are adding the type attribute. For WP Fastest Cache you should go to wp-content/plugins/wp-fastest-cache/inc folder and open js-utilities.php then search for text/javascript and delete it with the attribute. I had that warning on W3 Validator and fixed it that way, also be aware that when you will update plugin that change could be reverted, to disable plugin update you can edit wpFastestCache and change plugin version to something like this 10.0.8.7.7

You can optimize HTML code of your site as you want in 2 steps:

  • Install this plugin: https://wordpress/plugins/autoptimize/
  • Enable in the plugin options 'Optimize HTML Code?'
  • In functions.php of your current wordpress theme apply next code:

    add_filter('autoptimize_html_after_minify', function($content) {

        $site_url = 'https://bulk-editor';    
        $content = str_replace("type='text/javascript'", ' ', $content);
        $content = str_replace('type="text/javascript"', ' ', $content);
    
        $content = str_replace("type='text/css'", ' ', $content);
        $content = str_replace('type="text/css"', ' ', $content);
    
        $content = str_replace($site_url . '/wp-includes/js', '/wp-includes/js', $content);
        $content = str_replace($site_url . '/wp-content/cache/autoptimize', '/wp-content/cache/autoptimize', $content);
        $content = str_replace($site_url . '/wp-content/themes/', '/wp-content/themes/', $content);
        $content = str_replace($site_url . '/wp-content/uploads/', '/wp-content/uploads/', $content);
        $content = str_replace($site_url . '/wp-content/plugins/', '/wp-content/plugins/', $content);    
        return $content;    }, 10, 1);
    

    and do not forget to change $site_url to your site link without slash on the end

发布评论

评论列表(0)

  1. 暂无评论