Depending on the script and what it does, you might want to defer them or load them asynchronously. Defered scripts are executed only after a page has finished loading completely, so if your script needs to be executed during page loads, an async attribute would be more appropriate.

Keeping this in mind, the function below will allow you to add a defer or async attribute to selective scripts. Let’s see how this can be achieved:

Code Explanation: This function adds the defer or async attributes to the script tags by adding a filter to the wordpress script_loader_tag.

We start by saving the unique names of scripts that need to use defer and async in an array and then use a foreach loop to run through these arrays. Each time the loop runs, it tries to find the position of the unique filename in the script tags using the strpos (string position) function. If the strpos function returns TRUE (indicating the position of the unique string has been found in the script tag), a defer or async attribute is added using the PHP str_replace (string replace) function. If not, the tag is returned without any modifications.