The trick is to tell CloudFlare that you don’t want your script loaded asynchronously. To do that, you need to add an attribute to the script element, as documented on this CloudFlare support page:
NB: order is very important here — the
data-cfasync attribute must come before the
src attribute, or CloudFlare will ignore it! No, that’s not very helpful…
Anyway, adding that attribute to the script element for a WordPress script you’ve carefully enqueued using the recommended procedures isn’t as straightforward as you might think. wp_enqueue_script() doesn’t have any way to specify additional script attributes, and WordPress are still talking about how they might allow that.
So the approach I’ve come up with for scripts that spill onto the page footer is to:
- jump in ahead of the page footer scripts
- remove my script from the script queue
- output my own script element, with the special
No doubt you could do the same for scripts that spill onto the page in the header, just by changing the filter to be hooked. So here’s some code that does it:
And job is done, at the appropriate time, not when CloudFlare reckons it’s OK to run it. For a real live example, take a look at the little plugin I wrote to stop CloudFlare Rocketscript messing up scripts for my Flexible Map plugin.