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

烂漫一生 提交于 2020-01-05 08:50:29

问题


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 );

回答1:


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.



来源:https://stackoverflow.com/questions/42888357/how-to-bypass-cloudflare-rocket-script-if-wp-enqueue-script-is-used-to-add-scrip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!