Последнее обновление – 15 января 2023 в 16:09
Чтобы снять предупреждение HTML-валидатора “The type attribute is unnecessary for JavaScript resources”, можно пойти двумя путями. Как всегда есть простой и очень простой способ.
Вообще, валидатор показывает, какой скрипт вызывает такое предупреждение, которое означает, что атрибут “type” не является необходимым или обязательным для js-скриптов. Вот пример на скриншоте.
Достаточно найти его в файлах рабочей темы сайта и удалить участок кода, отмеченный на скрине красной рамкой. То есть, если ранее код скрипта, например, выглядел так:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
То теперь будет выглядеть следующим образом:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
Как видите, ничего сложного, необходимо лишь найти js-скрипт. А далее, дело техники.
Однако, есть и альтернатива. На помощь, как всегда, приходит файл functions.php. Несколько строчек кода спасут положение, когда нет желания копаться в файлах темы или установлены внешние скрипты.
# удалить атрибут type у scripts и styles
add_action( 'template_redirect', function(){
ob_start( function( $buffer ){
$buffer = str_replace( array( 'type="text/javascript"', "" ), '', $buffer );
$buffer = str_replace( array( 'type="text/css"', "" ), '', $buffer );
return $buffer;
});
});
Кроме того, дополнив содержимое файла functions.php этим кодом, вы сможете снять и такое предупреждение валидатора – “The type attribute for the style element is not needed and should be omitted”.
Всем WEB!
Оптимизация
Друзья, плюсаните, вдруг пригодится!
Add following code to your theme’s functions.php
add_action( 'template_redirect', 'prefix_remove_template_redirect', 10, 2);
function prefix_remove_template_redirect(){
ob_start( function( $buffer ){
$buffer = str_replace( array(
'<script type="text/javascript">',
"<script type='text/javascript'>",
"<script type='text/javascript' src=",
'<script type="text/javascript" src=',
'<style type="text/css">',
"' type='text/css' media=",
'<style type="text/css" media',
"' type='text/css'>"
),
array(
'<script>',
"<script>",
"<script src=",
'<script src=',
'<style>',
"' media=",
'<style media',
"' >"
), $buffer );
return $buffer;
});
};
This will change <script type="text/javascript">
to <script>
And will change <style type="text/css">
to <style>
. It can be done by script_loader_tag
but its given theme check validation error.
Update:
From WordPress 5.3, You can use following.
function theme_name_setup() {
add_theme_support( 'html5', array( 'script', 'style' ) );
}
add_action( 'after_setup_theme', 'theme_name_setup' );
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.
asked Dec 5, 2017 at 19:05
5
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' ] );
}
);
answered Nov 28, 2019 at 14:24
Jacob PeattieJacob Peattie
41.1k10 gold badges45 silver badges59 bronze badges
5
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 );
}
answered Dec 5, 2017 at 21:37
David SwordDavid Sword
3,2971 gold badge12 silver badges29 bronze badges
8
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 );
}
answered Dec 20, 2017 at 15:54
1
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.net/manual/en/function.ob-start.php
- http://php.net/manual/en/function.ob-end-flush.php
answered May 24, 2018 at 2:22
firxworxfirxworx
2411 silver badge1 bronze badge
3
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 );
}
}
answered Nov 6, 2018 at 19:31
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 );
}
nmr
4,4332 gold badges15 silver badges25 bronze badges
answered May 1, 2019 at 9:42
1
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 ); }
butlerblog
4,8263 gold badges23 silver badges41 bronze badges
answered Nov 28, 2019 at 12:30
1
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
answered Dec 5, 2019 at 23:13
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
answered Mar 18, 2018 at 22:07
You can optimize HTML code of your site as you want in 2 steps:
- Install this plugin: https://wordpress.org/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.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);
and do not forget to change $site_url to your site link without slash on the end
answered May 10, 2018 at 11:54
realmag777realmag777
1,6641 gold badge11 silver badges9 bronze badges
В html5 убрали атрибут type у тэга script. Теперь чтобы ваш код был валидным, нужно убрать его из кода. В Битриксе библиотека скриптов генерируется автоматически и нет настроек которые бы позволили убрать этот атрибут в административной панеле.
Для решения этой проблемы, можно воспользоваться предобработчиком, встроенным в ядро системы. Для этого надо добавить следующий код в bitrix/php_interface/init.php (Если у вас в системе нет такого файла, создайте его, он автоматически будет подгружен системой. init.php служит для того, что бы подключать к системе пользовательские функции, скрипты и обработчики):
AddEventHandler("main", "OnEndBufferContent", "delete_type"); function delete_type(&$content) { $content = str_replace(" type="text/javascript"", false, $content); }
The async attribute is boolean: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. As a boolean attribute, it does not need to be passed any value such as true or 1 to activate the async property.
For classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available.
For module scripts, if the async attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available.
<script async src="app.js"></script>
<script async type="module">
/* JavaScript module code here */
</script>