How do you force an analytics script to run 1st before ads or any other scripts?

contract

We're all gunna mine it brah.
Joined
Jun 2, 2015
Messages
410
Likes
451
Degree
2
Had G analytics in footer and it stopped tracking accurately because advertisements were loading.

I moved it to the header, hoping it works.

Is there another css/html/php condition that says, "hey, this script fires first"...?
 
CSS has nothing to do with it. You can only make scripts run later, not first, by adding tags like "defer" and "async" in the HTML script tags. Defer means to run after everything else loads and Async means to run asynchronously along side everything else, which tends to mean later but there's no guaranteed order.

Your best move is to do what you did, place it in the header above the call to the ad script.

I'm guessing it's the case that you're using Wordpress and some ad network's Wordpress plugin to load the ad script. In this case the plugin is enqueueing the script to be loaded (if done properly) rather than hooking it into the wp_head();. If this is the case, and you have a custom theme, you can enqueue your analytics code too, and set the priority to be earlier than the plugin does. Setting your priority to 0 would likely work.

Another way, if not using a plugin, would be to enqueue your ad script and make it have your analytics script as a dependency, meaning it will load after the analytics ad.

Let this put you on the trail: https://developer.wordpress.org/reference/functions/wp_enqueue_script/

Look at the User Contributed Notes at the bottom to get a handle on how it works. Your theme, in functions.php is likely enqueuing scripts and CSS styles. You have to register them then enqueue them. You can enqueue them in the order you wish, and if you can't see the order due to plugins getting involved, you can set the priority earlier and earlier until you confirm it's working.

That's the "right" and fancy way of doing it. Moving the script to the header and before the ad script will also get the job done if there's no plugins involved. Even if there are, you can just put the analytics script before the wp_head(); hook and it should work the same. Enqueued styles and scripts are injected into the header through that same hook.
 
Back