“The editor has encountered an unexpected error” After add defer tag to java script
-
21-04-2021 - |
Question
I added below script to add defer tag in javascripts. Once it added to function.php Gets error on create post "The editor has encountered an unexpected error." I cannot create or edit post. How can i add defer tag to javascripts without affecting to the editor. I don't have mush experience in coding. Thanks.
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'jquery-core' !== $handle )
return $tag;
return str_replace( ' src', ' defer="defer" src', $tag );
}, 10, 2 );
console errors are
TypeError: d.media is not a function wp-includes/js/dist/media-utils.min.js?ver=9ad24b42cc69f241229ded4dc61409fb:2:6432) wp-includes/js/dist/vendor/react-dom.min.js?ver=16.9.0:63:107) and more..
Solution
Seeing as your aim is to improve loading on the front end, the best approach would be to simply not add the defer
attribute when loading in the admin area, like so.
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'jquery-core' !== $handle ) {
return $tag;
}
if ( ! is_admin() ) {
$tag = str_replace( ' src', ' defer="defer" src', $tag );
}
return $tag;
}, 10, 2 );
As the editor has a number of scripts, often depending on other scripts already loading, it's generally not a good idea to try and use async
or defer
in the admin.