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

I am looking to enable CloudFlare’s RocketLoader feature that enables asynchronous loading of Javascript for my WordPress site. The problem, however, is that there is one plugin for that I want to be loaded normally.

From a technical point of view, according to https://www.cloudflare.com/wiki/Rocket_Loader, I simply need to change any script tag I want ignored to have the data-cfasync="false" attribute as follows: <script data-cfasync="false" src="/javascript.js"></script>

Read More

Unfortunately, I can’t seem to figure out how to do this for plugins that are automatically loaded by WordPress.

Any ideas?

Related posts

Leave a Reply

1 comment

  1. 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.