0

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

2
  • Why are you trying to defer scripts? Oct 3, 2020 at 15:07
  • When i check site speed on Gtmetrix, it says "JavaScript is parsed during initial page load. Defer parsing JavaScript to reduce blocking of page rendering." So, i tried with above code and it works well. But got error on above. Any other ways to Defer parsing JavaScript ?
    – Chadsmith
    Oct 3, 2020 at 15:16

1 Answer 1

0

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.

1
  • Great. It works well as i expected. Thank you..
    – Chadsmith
    Oct 4, 2020 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.