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
W3C 유효성 검사기는 Wordpress 사이트 나 널리 사용되는 cm에 대해 오류없이 거의 반환하지 않습니다. 매년 점점 악화되고있는 것 같습니다. 유효성 검사기 (imho)는 몇 가지 기본적인 오류 ( alt태그를 잊어 버리거나 태그를 닫는 것을 잊어 버리는 것과 같은)를 드러내는 도구로 사용해야하지만, 표준으로 생각해서는 안됩니다.
David Sword

그들은 017 년 12 월 2 일 이후에 내 테마가 오류 / 경고 무료가되기 전에 그것을 소개했다. 그것들을 제거 할 방법이 있어야합니다.
WP 중급

1
script_loader_tag후크를 살펴보면 str_replace()제거 할 수 있습니다.
David Sword

이것들은 오류 가 아니라 단지 경고 일뿐 입니다. 귀하의 사이트는 여전히 유효합니다.
swissspidy 2012 년

당신은 또한 다음과 같은 답을 확인하실 수 있습니다 - stackoverflow.com/a/53380692/2611955
Jahirul 이슬람 Mamun

답변:


16

각각의 후크를 사용하여 'ed 스크립트 및 스타일 type='*'에서 속성 및 값을 제거 할 수 있습니다 .wp_enqueue*_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 중급

5의 소스를 추적하고 태그를 편집 할 수 있는지 확인할 수 있습니다. 나는 그들이 아마 사용하지 않을 것이라고 다시 추측합니다 wp_enqueue. 코드와 플러그인 참조와 함께 완고한 5 개의 왼쪽을 반영하기 위해 원래 게시물에 UPDATE를 추가하는 것이 좋습니다. 더 도움이 될 수 있습니다.
David Sword

선생님, 이번에는 이미지의 오류를 업데이트했습니다.
WP 중급

13

워드 프레스 5.3에서는이를 달성하기위한 훨씬 간단한 방법을 소개합니다. script및에 대한 HTML 5에 대한 테마 지원을 등록 style하면 type=""속성이 생략됩니다.

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

감사했습니다.
Michael Rogers

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 중급

3

style_loader_tag하고 script_loader_tag그들이 무엇을위한 테마 / 플러그인 적절한 대기열 기능을 사용하는 경우에, 워드 프레스가 생성하는 마크 업 작업을해야처럼 이상에 접근한다.

당신이 플러그인의 기분을 상하게 한 경우 그 협조하지 않습니다 (IIRC 제트 팩은 / 내 기억 이후 새로운 버전이 개정하지 않는 한! 범죄자이었다), 그리고 당신이 단호 방문자가 가능성이되지 않도록 사실에도 불구하고이 문제 해결에 대한 어떤 식 으로든 영향을 받으면 (브라우저가 페이지를 잘 렌더링합니다!) 항상 출력 버퍼링을 사용할 수 있습니다.

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가 클라이언트 브라우저로 전송되기 전에 Wordpress의 전체 "최종"출력에서 실행 중 입니다.

출력 버퍼링은 시작 ( wp_loaded후크) 에서 켜집니다 . 즉, wp + theme + plugins + 등이 완전히로드 된 shutdown직후, PHP가 실행을 종료하기 직전에 실행되는 마지막 순간 ( 후크) 에서 꺼집니다 . 정규식은 모든 것을 통해 작동해야 하며 많은 내용이 될 수 있습니다!

위 의 style_loader_tagscript_loader_tag접근 방식은 매우 작은 문자열 (태그 자체)에서만 정규 표현식을 실행하므로 성능 영향은 무시할 수 있습니다.

비교적 정적 인 콘텐츠가 있고 캐싱 레이어를 사용하면 성능 문제를 완화하려고 할 수 있다고 가정합니다.

PHP 매뉴얼 참조 :


이것은 최선의 답변이며 오류없이 올바르게 작동합니다. 고마워요
Ivijan Stefan Stipić

유일한 작동 솔루션
Timur Gafforov

궁금한 점이 있으면 WordPress는 인라인 스크립트에 태그를 추가 할 때 style_loader_tag또는 script_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 );
}

Jeevan WPSE에 오신 것을 환영합니다. 문제가 해결되는 이유와 작동 방식에 대한 답변과 함께 설명을 포함하면 도움이됩니다.
butlerblog

0

글쎄, 내가 언급 한 많은 다른 코드와 여기에 언급 된 코드를 시도했기 때문에 여전히 text/javascriptWordPress 핵심 파일과 다른 플러그인 및 인라인 자바 스크립트 코드의 흔적이 있습니다. 이 코드를 테스트 한 후 모든 것이 해결되었습니다.

// 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 Validator에 대한 경고가 있었으며 그 방법으로 수정했습니다. 변경 사항을 되돌릴 수있는 플러그인을 업데이트 할 때 플러그인 업데이트를 비활성화하려면 wpFastestCache를 편집하고 플러그인 버전을 10.0.8.7.7과 같이 변경할 수 있습니다.


-1

2 단계로 원하는대로 사이트의 HTML 코드를 최적화 할 수 있습니다.

  • 이 플러그인을 설치하십시오 : https://wordpress.org/plugins/autoptimize/
  • 플러그인 옵션 'HTML 코드 최적화'에서 활성화하십시오.
  • 현재 워드 프레스 테마의 functions.php에서 다음 코드를 적용하십시오.

    add_filter ( 'autoptimize_html_after_minify', 함수 ($ 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

아래 함수를 사용하여 링크 및 스크립트 태그에서 유형 속성을 제거 할 수 있습니다.

link태그 에서 type = text / css를 제거하기 위해 functions.php에 아래 함수를 붙여 넣으십시오.

/ * 스타일 시트에서 " 'type = text / css'"속성 제거 * /
함수 wpse51581_hide_type ($ src) {
    반환 str_replace ( "type = 'text / css'", '', $ src);
}
add_filter ( 'style_loader_tag', 'wpse51581_hide_type');

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

아래에서 type = 'text / javascript'를 제거하기 위해 functions.php에 함수를 붙여 넣으십시오. script

// * 스크립트 및 스타일에서 유형 태그 제거
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);
}

정답은 맞지만 여전히 누군가 부정 투표
Infoconic
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.