How do I add custom attributes to javascript tags in WordPress?

The following solution assumes that your plugins are using wp_enqueue_script() to insert scripts into the HTML code. If they don’t they are broken by design and we cannot change the script tag.

This code works like the one in this answer, in fact, it is almost a duplicate …

First make two lists of all script URIs you want be ignored or not ignored by the rocket loader script. Then fill the $optimize and the $ignore arrays in the following script with these URIs.

function rocket_loader_attributes( $url )
{
    $optimize = array (
        'http://example.com/nr1.js',
        'http://example.com/nr2.js'
    );
    $ignore = array (
        'http://example.com/nr3.js',
        'http://example.com/nr4.js'
    );

    if ( in_array( $url, $optimize ) )
    { // this will be optimized
        return "$url' data-cfasync="true";
    }

    if ( in_array( $url, $ignore ) )
    { // this will be ignored
        return "$url" data-cfasync="false";
    }

    return $url;
}
add_filter( "clean_url', 'rocket_loader_attributes', 11, 1 );

You can create a plugin with this code or – second best option – add it to your theme’s functions.php.

Leave a Comment