从WordPress添加的脚本和样式标签中删除类型属性


15
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

这些错误是W3C的一些新功能,并且仅在最近3-4天才开始出现。在此处输入图片说明

我们将这样的脚本排入队列→

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

我们可以通过上述入队方法以某种方式解决此问题吗?

更新→

这些是实际的错误。在红色框中是来自W3的总缓存。在此处输入图片说明


5
对于Wordpress网站或任何流行的cms,W3C验证程序很少返回无错误的消息。似乎每年都会变得越来越糟。验证器(imho)应该用作揭示一些基本错误的工具(例如,忘记alt标签或忘记关闭标签),但不应像以前那样被视为标准。
David Sword

他们在017年12月2日之后推出了它。在那之前,我的主题是错误/警告免费。应该有一些摆脱它们的方法。
WP中级

1
查看script_loader_tag挂钩,您可能可以str_replace()删除它们。
David Sword

值得指出的是,这些只是警告,而不是错误。您的网站仍将验证。
swissspidy

Answers:


16

您可以使用相应的钩子type='*'wp_enqueue'ed脚本和样式中删除属性和值*_loader_tag

以下为我工作:

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 );
}

我试过了,但是并没有解决问题。可能是我们需要一些操纵。
WP中级

1
我推测您的某些插件脚本(例如带有defer标记的缓存插件脚本)可能未使用wp_enqueue_script,因此将不再使用*_loader_tag。你可以请确认我的片段添加,您的网站的源代码,这custom.js确实有type='text/javascript'不动呢?
David Sword

否。我删除了w3总缓存插件。3/8错误消失了,但仍然有5个错误。
WP中级

好了,您可以找到这五个标签的来源,并查看是否可以编辑标签。我再次推测它们可能不使用wp_enqueue。我建议在您的原始帖子中添加一个UPDATE,以反映代码和插件引用中剩下的5个顽固的内容-也许可以提供更多帮助。
David Sword

先生,这次更新了图片错误。
WP中级

13

WordPress 5.3引入了一种相当简单的方法来实现这一目标。通过为script和注册HTML 5的主题支持style,该type=""属性将被省略:

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

工作正常,谢谢。
迈克尔·罗杰斯

1
这是正确的方法。
Ankit Chauhan

2
好一个!这应该是公认的答案。

3

从土壤/根插件获得了这一点。大部分时间都做得很好。

    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 );
}

您是否尝试过
WP Intermediate

3

在主题/插件使用适当的入队功能的情况下,上面的style_loader_tagscript_loader_tag方法似乎适用于Wordpress生成的任何标记。

如果您有不兼容的问题插件(除非IIRC Jetpack是/曾经是违法者,除非自从我回忆起已对此进行了修订,否则是一个较新的版本!),并且您坚决解决此问题,尽管您的访问者不太可能受到任何影响(他们的浏览器将完美渲染页面!),您可以始终全力以赴并使用输出缓冲:

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 );
}

请注意,虽然这是一个解决方案,但效率不是很高。preg_replace()对于每个请求,您都需要先运行Wordpress的整个“最终”输出,然后再将其发送到客户端的浏览器。

输出缓冲在开始(wp_loaded钩子)时打开,即在wp +主题+插件+等已完全加载时打开,并在最后一刻关闭(shutdown钩子),这在PHP关闭执行之前触发。正则表达式必须处理所有内容,这可能是很多内容!

上面的style_loader_tagand script_loader_tag方法仅在很小的字符串(标签本身)上运行正则表达式,因此对性能的影响可以忽略不计。

我想如果您具有相对静态的内容并使用了缓存层,则可以尝试减轻性能问题。

php手册参考:


这是最佳答案,并且只能正常工作且没有错误。谢啦。
Ivijan StefanStipić18年

唯一
可行的

如果有人好奇,WordPress在为嵌入式脚本添加标签时似乎不使用style_loader_tagscript_loader_tag过滤器。developer.wordpress.org/reference/classes/wp_scripts/…–<script>
firxworx

1

这对我有很大帮助:

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

感谢CSS-tricks(LeoNovais):https ://css-tricks.com/forums/topic/clean-up-script-tags-in-wordpress/#post-246425


上面具体提到的OP实际位于此处:css-tricks.com/forums/topic/clean-up-script-tags-in-wordpress / ...注意:该脚本已涂黑,但是通过选择文本,您可以阅读它,并如上所述发布。LeoNovais没有提供任何其他解释。我不知道为什么CSS Tricks屏蔽了他的脚本。
SherylHohman

1

根据script-loader.php中的代码,当通过脚本和样式参数添加html5主题支持时,将省略type属性。

请参阅以下链接:

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' );

0

从@ realmag77构建。这将利用Autoptimize插件来过滤掉所有类型的属性,但如果未安装和激活它,则不会中断。回退效果很好,但是不会过滤通过插件加载的那些脚本和样式表。我不知道如何过滤它们,而是通过使用“自动优化”部分。

/* ==========================================
   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 );
    }
}

0
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 );
}

欢迎来到WPSE,Jeevan。如果在回答中包含解释说明为什么可以解决问题以及其工作方式,这将很有帮助。
butlerblog

0

好吧,因为我尝试了很多其他代码以及此处提到的代码,所以仍然有text/javascript来自WordPress核心文件以及其他插件和内联javascript代码的痕迹。测试此代码后,所有问题均已解决:

// 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 );
}

希望它可以帮助一些:)

谢谢


-1

如果您使用WP Fastest Cache遇到这种情况,则可以在插件PHP脚本中手动删除type属性,这也应该与其他插件一起使用,但是我不知道文件在哪里添加type属性。对于WP Fastest Cache,您应该转到wp-content / plugins / wp-fastest-cache / inc文件夹并打开js-utilities.php,然后搜索text / javascript并使用属性将其删除。我在W3验证程序上有该警告并以这种方式解决,也请注意,当您更新插件时,该更改可以恢复,要禁用插件更新,您可以编辑wpFastestCache并将插件版本更改为以下10.0.8.7.7。


-1

您可以按照以下两个步骤来优化网站的HTML代码:

  • 安装此插件:https : //wordpress.org/plugins/autoptimize/
  • 在插件选项中启用“优化HTML代码?”
  • 在当前wordpress主题的functions.php中,应用以下代码:

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

        $site_url = 'https://bulk-editor.com';    
        $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);

    并且不要忘了将$ site_url更改为您的站点链接,而不必在最后加斜杠


-1

您可以使用以下功能从链接和脚本标签中删除类型属性。

将以下函数粘贴到functions.php中,以从link标记中删除type = text / css

/ *从样式表中删除属性“'type = text / css'” * /
函数wpse51581_hide_type($ src){
    返回str_replace(“ type ='text / css'”,``,$ src);
}
add_filter('style_loader_tag','wpse51581_hide_type');

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

将以下函数粘贴到functions.php中,以从中删除type ='text / javascript' script

// *从脚本和样式中删除类型标签
add_filter('script_loader_tag','codeless_remove_type_attr',10,2);
函数codeless_remove_type_attr($ tag,$ handle){
    返回preg_replace(“ / type = ['\”] text \ /(javascript | css)['\“] /”,'',$ tag);
}

答案是正确的,但仍然有人投了反对票
Infoconic
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.