0

I'm trying to incorporate a Defer Parsing of JavaScript function into my functions.php file. When I do, the site still works fine, but in wp-admin, anything involving Gutenberg wont' load and I just get the white screen of death. Any idea if this code is bad?

// Defer Parsing of Javascript
function defer_parsing_of_js ( $url ) {
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) ) return $url;
    return str_replace( ' src', ' defer src', $url );
}
add_filter( 'script_loader_tag', 'defer_parsing_of_js', 10 );

1 Answer 1

0

The page where you probably downloaded this code has a comment in it that solved it. Use this instead:

function defer_parsing_of_js( $url ) {
    if ( is_user_logged_in() ) return $url; //don't break WP Admin
    if ( FALSE === strpos( $url, '.js' ) ) return $url;
    if ( strpos( $url, 'jquery.js' ) ) return $url;
    return str_replace( ' src', ' defer src', $url );
}
add_filter( 'script_loader_tag', 'defer_parsing_of_js', 10 );

Source: https://kinsta.com/blog/defer-parsing-of-javascript/ (Answer by Dean)

3
  • Thanks, but unfortunately, that actually threw an error right here as follows: Parse error: syntax error, unexpected 'src’' (T_STRING), expecting ',' or ')' in /www/webroot/mysite/wordpress/wp-content/themes/my-theme/functions.php on line 548 That would be: return str_replace( ‘ src’, ‘ defer src’, $url );
    – Adam Bell
    Nov 25, 2019 at 2:17
  • Thats actually a very basic error type imo. It's when you forget a ; or ) or } or $ or something like that. In this case the quotes of the original article were of a weird type. I replaced them, can you try again with current code?
    – Snuwerd
    Nov 25, 2019 at 11:24
  • 1
    Yes, that made the difference. Thank you.
    – Adam Bell
    Nov 25, 2019 at 19:14

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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