# Defer Selected Scripts

> Adds the defer attribute to the front-end scripts you list by handle, so they no longer block page rendering.

- Type: PHP
- Runs: Frontend only
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: performance, javascript, defer
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/defer-selected-scripts/

## Code

```php
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
    // Script handles that are safe to defer.
    $handles = array( 'comment-reply' );

    if ( ! in_array( $handle, $handles, true ) || preg_match( '/\s(defer|async)[\s>=]/', $tag ) ) {
        return $tag;
    }

    return str_replace( ' src=', ' defer src=', $tag );
}, 10, 2 );
```

## Notes

Only defer scripts that no inline script depends on immediately. Find handles with a plugin such as Query Monitor.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Defer Selected Scripts" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
