Cloudflare's Rocket Loader + Wordpress -> Ignore scripts?

こ雲淡風輕ζ 提交于 2019-12-04 17:20:59

I have found the solution for this!

As it's written in this article: Controlling Cloudflare Rocket Loader

Your script was almost right, but the manual mode is broken. You need to switch to automatic mode, and then make some modifications:

function rocket_loader_attributes_start() {
    ob_start();
}

function rocket_loader_attributes_end() {
    $script_out = ob_get_clean();
    $script_out = str_replace(
      "type='text/javascript' src='{rocket-ignore}", 
      'data-cfasync="false"'." src='", 
      $script_out);  
    print $script_out;
}

function rocket_loader_attributes_mark($url) {
    // Set up which scripts/strings to ignore
    $ignore = array (
        'script1.js'
    );
    //matches only the script file name
    preg_match('/(.*)\?/', $url, $_url);
    if (isset($_url[1]) && substr($_url[1], -3)=='.js') {
      foreach($ignore as $s) {
         if (strpos($_url[1], $s)!==false)
           return "{rocket-ignore}$url";
      }
      return "$url' data-cfasync='true";
    }

    return "$url";

}
if (!is_admin()) {
  add_filter( 'clean_url', 'rocket_loader_attributes_mark', 11, 1);
  add_action( 'wp_print_scripts', 'rocket_loader_attributes_start');
  add_action( 'print_head_scripts', 'rocket_loader_attributes_end');
}

Notice in the example that the tag does not have the type='text/javascript' attribute. For some reason Rocket Loader requires data-cfasync='false' to be used without the type='text/javascript'... a bug?

Your code does add the data-cfasync='false' attribute, but does not override the WordPress behaviour of adding the type='text/javascript' attribute also, which makes Rocket Loader not to "ignore" your script.

It might be tricky to override this WordPress behaviour since the relevant code does not support a filter...

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