Defer Parsing of JavaScript in WordPress

Looking for a way to defer JavaScript files, loading its JS content in the background without holding the loading of the page.. Important for Google Page Insight score.

And since I like to make my own scripts or search for code examples that could help me achieve my goals..

I’ve found one which works fine here but was not working propertly for me since I was getting errors of JS not been defined and also then when I wanted to make a new POST I would get a blank page..

So, I decided to edit it a bit and add little checks to make sure it would work correctly in the current version of WordPress I am running which is v5.4.2

I was having issues beside adding new POSTs in de admin page also had issues with “syntaxhighlighter” loading a little late and not loading its themes or doing it but too late after their global variables was called giving an error.

Put this code in your theme functions or in a base plugin like the one I talked about WP redirect users from dashboard but admins make sure you change the function name as one you like and that you name it in the add_filter method .

function boostrap4_techuserspace_theme_defer_js( $url ){
    // we arent in admin page
    if (! is_admin() ) {
        if ((false === strpos($url, '.js')) || (false !== strpos($url, 'syntaxhighlighter'))) { // not our file
            return $url;
        }
        // Must be a ', not "!
        return "$url' defer='defer";
    }
    
    return $url;
}

Then after you put it in a place you decided to go.. then add a filter so it loads with WordPress.

add_filter( 'clean_url', 'boostrap4_techuserspace_theme_defer_js', 11, 1 );

That’s it.. it makes sure that the code doesn’t load in Admin Page and that “syntaxhighlighter” is loaded properly.. which don’t add the “defer” attribute when loading the page, working correctly , defering Javascript in WordPress made easy..

I am just a Tech User just like you. bye for now!