Search code examples
phpwordpresscloudflarerocketscript

How to bypass CloudFlare rocket script if wp_enqueue_script is used to add scripts?


I just googled this but didn`t retrieve any specific info. I have such code on a PHP template for WordPress:

<?php wp_enqueue_script( 'jquery-carousel', get_template_directory_uri().'/js/jquery.carouFredSel-6.2.1-packed.js', array('jquery'),'',true); ?>

And I want to add CloudFlare ignore for Rocketloader data-cfasync="false" just before the 'src' attribute of jquery.carouFredSel-6.2.1-packed.js

What can I do?

Regards

Edit:

A big thanks to @Mary for the code. So the solution for this is to add this function in functions.php :

function add_data_attribute( $tag, $handle, $src ) {
    if ( 'jquery-carousel' !== $handle )
       return $tag;

    return str_replace( ' src', ' data-cfasync="false" src', $tag );
}

add_filter( 'script_loader_tag', 'add_data_attribute', 10, 3 );

If there is a need to add more tags like 'jquery-carousel1', 'jquery-carousel2' to this function, the code looks like this:

function add_data_attribute( $tag, $handle, $src ) {
    if( ! in_array( $handle, array( 'jquery-carousel', 'jquery-carousel1', 'jquery-carousel2' ) ) )
       return $tag;

    return str_replace( 'src', 'data-cfasync="false" src', $tag );
}

add_filter( 'script_loader_tag', 'add_data_attribute', 10, 3 );

Solution

  • You could try filtering with script_loader_tag.

    function add_data_attribute( $tag, $handle, $src ) {
        if ( 'jquery-carousel' !== $handle )
           return $tag;
    
        return str_replace( ' src', ' data-cfasync="false" src', $tag );
    }
    
    add_filter( 'script_loader_tag', 'add_data_attribute', 10, 3 );
    

    This way you can target your specific enqueued script.