# Subresource Integrity for Scripts and Styles From CDNs

> Adds integrity and crossorigin attributes to the CDN-hosted scripts and stylesheets you list, so browsers refuse to run them if the CDN copy is ever tampered with.

- Type: PHP
- Runs: Frontend only
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: sri, cdn, scripts
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/sec-subresource-integrity/

## Code

```php
// Handle => integrity hash of the exact file that handle loads.
$wpide_sri_hashes = array(
    'example-cdn-script' => 'sha384-REPLACE_WITH_THE_FILE_HASH',
);

$wpide_add_sri = function ( $tag, $handle ) use ( $wpide_sri_hashes ) {
    if ( empty( $wpide_sri_hashes[ $handle ] ) || false !== strpos( $tag, 'integrity=' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
        return $tag;
    }

    $tags = new WP_HTML_Tag_Processor( $tag );

    while ( $tags->next_tag() ) {
        if ( in_array( $tags->get_tag(), array( 'SCRIPT', 'LINK' ), true ) && ( $tags->get_attribute( 'src' ) || $tags->get_attribute( 'href' ) ) ) {
            $tags->set_attribute( 'integrity', $wpide_sri_hashes[ $handle ] );
            $tags->set_attribute( 'crossorigin', 'anonymous' );
            break;
        }
    }

    return $tags->get_updated_html();
};

add_filter( 'script_loader_tag', $wpide_add_sri, 20, 2 );
add_filter( 'style_loader_tag', $wpide_add_sri, 20, 2 );
```

## Notes

Get the hash for each exact file version from the CDN (for example the "Copy SRI" button on cdnjs) and update it whenever you change the version.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Subresource Integrity for Scripts and Styles From CDNs" 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/
