“The editor has encountered an unexpected error” After add defer tag to java script

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..

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x